akupriyanovhse

поиск глаз

Mar 11th, 2026
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.53 KB | None | 0 0
  1. import cv2
  2. import mediapipe as mp
  3. from mediapipe.tasks import python
  4. from mediapipe.tasks.python import vision
  5.  
  6.  
  7. def detect_eyes(image_path: str, output_path: str) -> None:
  8.     # 1. Читаем изображение через OpenCV
  9.     img_bgr = cv2.imread(image_path)
  10.     if img_bgr is None:
  11.         raise FileNotFoundError(
  12.             f"Не удалось прочитать изображение: {image_path}\n"
  13.             f"Проверь путь и попробуй сохранить файл в jpg или png."
  14.         )
  15.  
  16.     h, w = img_bgr.shape[:2]
  17.  
  18.     # 2. Переводим BGR -> RGB
  19.     img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
  20.  
  21.     # 3. Создаём объект MediaPipe Image из numpy-массива
  22.     mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img_rgb)
  23.  
  24.     # 4. Загружаем модель детектора лиц
  25.     base_options = python.BaseOptions(
  26.         model_asset_path="blaze_face_short_range.tflite"
  27.     )
  28.  
  29.     options = vision.FaceDetectorOptions(
  30.         base_options=base_options,
  31.         min_detection_confidence=0.5
  32.     )
  33.  
  34.     detector = vision.FaceDetector.create_from_options(options)
  35.  
  36.     # 5. Детекция
  37.     result = detector.detect(mp_image)
  38.  
  39.     if not result.detections:
  40.         print("Лица не найдены")
  41.         return
  42.  
  43.     print(f"Найдено лиц: {len(result.detections)}")
  44.  
  45.     for i, face in enumerate(result.detections, start=1):
  46.         bbox = face.bounding_box
  47.  
  48.         x = int(bbox.origin_x)
  49.         y = int(bbox.origin_y)
  50.         bw = int(bbox.width)
  51.         bh = int(bbox.height)
  52.  
  53.         # Рамка лица
  54.         cv2.rectangle(img_bgr, (x, y), (x + bw, y + bh), (255, 0, 0), 2)
  55.  
  56.         # В MediaPipe первые две keypoints — обычно глаза
  57.         for idx, kp in enumerate(face.keypoints[:2]):
  58.             px = int(kp.x * w)
  59.             py = int(kp.y * h)
  60.  
  61.             cv2.circle(img_bgr, (px, py), 7, (0, 255, 0), -1)
  62.  
  63.             label = "left_eye" if idx == 0 else "right_eye"
  64.             cv2.putText(
  65.                 img_bgr,
  66.                 label,
  67.                 (px + 8, py - 8),
  68.                 cv2.FONT_HERSHEY_SIMPLEX,
  69.                 0.55,
  70.                 (0, 255, 0),
  71.                 2
  72.             )
  73.  
  74.             print(f"{label}: ({px}, {py})")
  75.  
  76.     cv2.imwrite(output_path, img_bgr)
  77.     print(f"Результат сохранён в: {output_path}")
  78.  
  79.  
  80. if __name__ == "__main__":
  81.     detect_eyes("./img_in/tom.webp", "./img_out/result.jpg")
Advertisement
Add Comment
Please, Sign In to add comment