Download run.py from myned-ai/facepoints: direct link, hf CLI and curl.
- Browser
- Download file 2.45 kB
-
https://huggingface.co/myned-ai/facepoints/resolve/main/run.py
- Command line
-
hf download hf://myned-ai/facepoints/run.py
-
curl -L -o run.py https://huggingface.co/myned-ai/facepoints/resolve/main/run.py
2.45 kB
| """Detect the 620 points on every face OpenCV's YuNet finds in a photo and draw them.""" | |
| # Usage: python run.py photo.jpg [out.jpg] [--model DIR] | |
| # The model folder defaults to this file's folder (model.safetensors + config.json). | |
| # Works from a clone of the repository without installing it; YuNet is downloaded once into the | |
| # temp dir. Installed, the same script is `python -m facepoints.run`. | |
| import argparse | |
| import os | |
| import sys | |
| import tempfile | |
| import urllib.request | |
| import cv2 | |
| import numpy as np | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| if __package__ in (None, ""): # run as a file, not installed: make the clone importable | |
| sys.path.insert(0, os.path.dirname(HERE)) | |
| try: | |
| from facepoints import Detector, square_box # noqa: E402 | |
| except ModuleNotFoundError: | |
| sys.exit("facepoints is not importable: keep the folder named facepoints, or pip install -e .") | |
| YUNET_URL = ( | |
| "https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/" | |
| "face_detection_yunet_2023mar.onnx" | |
| ) | |
| CONFIDENT_PX = 4.0 # points with a smaller std are drawn green, the rest orange | |
| def main(photo, out, model_dir): | |
| """Find the faces, detect their points and write the drawing.""" | |
| yunet = os.path.join(tempfile.gettempdir(), "yunet_2023mar.onnx") | |
| if not os.path.exists(yunet): | |
| urllib.request.urlretrieve(YUNET_URL, yunet) | |
| finder = cv2.FaceDetectorYN.create(yunet, "", (320, 320), score_threshold=0.5) | |
| det = Detector(model_dir) | |
| img = cv2.imread(photo) | |
| finder.setInputSize((img.shape[1], img.shape[0])) | |
| _, faces = finder.detect(img) | |
| for f in [] if faces is None else faces: | |
| res = det.detect(img, square_box(*f[:4])) | |
| for (x, y), s in zip(res["points"], res["std"], strict=True): | |
| colour = (0, 255, 0) if s < CONFIDENT_PX else (0, 165, 255) | |
| cv2.circle(img, (int(round(x)), int(round(y))), 2, colour, -1) | |
| box = np.round(f[:4]).astype(int).tolist() | |
| print(f"face at {box}: median std {np.median(res['std']):.2f} px") | |
| cv2.imwrite(out, img) | |
| print("wrote", out) | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("photo") | |
| ap.add_argument("out", nargs="?", help="default: <photo>_points.jpg") | |
| ap.add_argument("--model", default=HERE, help="the model folder") | |
| a = ap.parse_args() | |
| main(a.photo, a.out or os.path.splitext(a.photo)[0] + "_points.jpg", a.model) | |