Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import mediapipe as mp
- from mediapipe.tasks import python
- from mediapipe.tasks.python import vision
- def detect_eyes(image_path: str, output_path: str) -> None:
- # 1. Читаем изображение через OpenCV
- img_bgr = cv2.imread(image_path)
- if img_bgr is None:
- raise FileNotFoundError(
- f"Не удалось прочитать изображение: {image_path}\n"
- f"Проверь путь и попробуй сохранить файл в jpg или png."
- )
- h, w = img_bgr.shape[:2]
- # 2. Переводим BGR -> RGB
- img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
- # 3. Создаём объект MediaPipe Image из numpy-массива
- mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img_rgb)
- # 4. Загружаем модель детектора лиц
- base_options = python.BaseOptions(
- model_asset_path="blaze_face_short_range.tflite"
- )
- options = vision.FaceDetectorOptions(
- base_options=base_options,
- min_detection_confidence=0.5
- )
- detector = vision.FaceDetector.create_from_options(options)
- # 5. Детекция
- result = detector.detect(mp_image)
- if not result.detections:
- print("Лица не найдены")
- return
- print(f"Найдено лиц: {len(result.detections)}")
- for i, face in enumerate(result.detections, start=1):
- bbox = face.bounding_box
- x = int(bbox.origin_x)
- y = int(bbox.origin_y)
- bw = int(bbox.width)
- bh = int(bbox.height)
- # Рамка лица
- cv2.rectangle(img_bgr, (x, y), (x + bw, y + bh), (255, 0, 0), 2)
- # В MediaPipe первые две keypoints — обычно глаза
- for idx, kp in enumerate(face.keypoints[:2]):
- px = int(kp.x * w)
- py = int(kp.y * h)
- cv2.circle(img_bgr, (px, py), 7, (0, 255, 0), -1)
- label = "left_eye" if idx == 0 else "right_eye"
- cv2.putText(
- img_bgr,
- label,
- (px + 8, py - 8),
- cv2.FONT_HERSHEY_SIMPLEX,
- 0.55,
- (0, 255, 0),
- 2
- )
- print(f"{label}: ({px}, {py})")
- cv2.imwrite(output_path, img_bgr)
- print(f"Результат сохранён в: {output_path}")
- if __name__ == "__main__":
- detect_eyes("./img_in/tom.webp", "./img_out/result.jpg")
Advertisement
Add Comment
Please, Sign In to add comment