You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gesture_rec/skeleton/mediapipe_detector.py

42 lines
1.6 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import cv2
import mediapipe as mp
import numpy as np
class MediaPipeDetector:
def __init__(self, model_complexity=1, min_detection_confidence=0.5):
self.mp_pose = mp.solutions.pose
self.pose = self.mp_pose.Pose(
static_image_mode=False,
model_complexity=model_complexity,
enable_segmentation=False,
min_detection_confidence=min_detection_confidence
)
self.mp_drawing = mp.solutions.drawing_utils
def detect(self, image):
"""Возвращает словарь с ключами: success, landmarks (33,4), pose_landmarks (для отрисовки)"""
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = self.pose.process(rgb)
if results.pose_landmarks:
h, w, _ = image.shape
landmarks = []
for lm in results.pose_landmarks.landmark:
x = lm.x * w
y = lm.y * h
z = lm.z
v = lm.visibility
landmarks.append([x, y, z, v])
landmarks = np.array(landmarks, dtype=np.float32)
return {'success': True, 'landmarks': landmarks, 'pose_landmarks': results.pose_landmarks}
else:
return {'success': False, 'landmarks': None, 'pose_landmarks': None}
def draw_landmarks(self, image, pose_landmarks):
"""Рисует скелет на копии изображения и возвращает её"""
if pose_landmarks is None:
return image.copy()
vis = image.copy()
self.mp_drawing.draw_landmarks(vis, pose_landmarks, self.mp_pose.POSE_CONNECTIONS)
return vis