Spaces:
Sleeping
Sleeping
| import cv2 | |
| import numpy as np | |
| from typing import List, Iterable, Optional | |
| from mediapipe.python.solutions.face_mesh import FaceMesh # Correct import | |
| def detect_landmarks(src: np.ndarray, is_stream: bool = False) -> Optional[List]: | |
| """ | |
| Given an image `src`, retrieves the facial landmarks associated with it. | |
| Works with Mediapipe 0.10+. | |
| """ | |
| with FaceMesh( | |
| static_image_mode=not is_stream, | |
| max_num_faces=1, | |
| refine_landmarks=True, | |
| min_detection_confidence=0.5, | |
| min_tracking_confidence=0.5 | |
| ) as fm: | |
| results = fm.process(cv2.cvtColor(src, cv2.COLOR_BGR2RGB)) | |
| if results.multi_face_landmarks: | |
| return results.multi_face_landmarks[0].landmark | |
| return None | |
| def normalize_landmarks(landmarks, height: int, width: int, mask: Iterable = None) -> np.ndarray: | |
| normalized_landmarks = np.array([ | |
| (int(landmark.x * width), int(landmark.y * height)) for landmark in landmarks | |
| ]) | |
| if mask is not None: | |
| normalized_landmarks = normalized_landmarks[mask] | |
| return normalized_landmarks | |
| def plot_landmarks(src: np.ndarray, landmarks: List, show: bool = False) -> np.ndarray: | |
| dst = src.copy() | |
| for x, y in landmarks: | |
| cv2.circle(dst, (x, y), 2, (0, 255, 0), cv2.FILLED) | |
| if show: | |
| print("Displaying image plotted with landmarks") | |
| cv2.imshow("Plotted Landmarks", dst) | |
| cv2.waitKey(0) | |
| cv2.destroyAllWindows() | |
| return dst |