-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
73 lines (59 loc) · 2.46 KB
/
Copy pathmain.py
File metadata and controls
73 lines (59 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import cv2
import numpy as np
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
# STEP 1: Configurar o detector no modo VIDEO
base_options = python.BaseOptions(model_asset_path="hand_landmarker.task")
options = vision.HandLandmarkerOptions(
base_options=base_options,
running_mode=vision.RunningMode.VIDEO,
num_hands=2)
detector = vision.HandLandmarker.create_from_options(options)
# STEP 2: Declaração e desenho e das hand connections
HAND_CONNECTIONS = [
(0,1),(1,2),(2,3),(3,4), # polegar (amarelo)
(0,5),(5,6),(6,7),(7,8), # indicador (azul)
(0,9),(9,10),(10,11),(11,12), # médio (verde)
(0,13),(13,14),(14,15),(15,16), # anelar (rosa)
(0,17),(17,18),(18,19),(19,20), # mínimo (cinza)
(5,9),(9,13),(13,17) # palma
]
def draw_landmarks_on_image(rgb_image, detection_result):
image = np.copy(rgb_image)
h, w, _ = image.shape # altura e largura para desnormalizar as coordenadas
for hand_landmarks in detection_result.hand_landmarks:
# Converte coordenadas normalizadas (0~1) para pixels
pontos = [
(int(lm.x * w), int(lm.y * h))
for lm in hand_landmarks
]
# Desenha as conexões (linhas entre os pontos)
for start, end in HAND_CONNECTIONS:
cv2.line(image, pontos[start], pontos[end], (0, 0, 255), 2)
# Desenha os pontos (landmarks)
for ponto in pontos:
cv2.circle(image, ponto, 5, (255, 255, 0), -1)
return image
# STEP 3: Abrir a câmera
cap = cv2.VideoCapture(0)
timestamp_ms = 0
with detector:
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
continue
# STEP 4: Converter frame para mp.Image (a API exige RGB)
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_image)
# STEP 5: Detectar (passando o timestamp)
detection_result = detector.detect_for_video(mp_image, timestamp_ms)
timestamp_ms += 1
# STEP 6: Desenhar e exibir
output_image = draw_landmarks_on_image(rgb_image, detection_result)
output_rgb_image = cv2.cvtColor(output_image, cv2.COLOR_RGB2BGR)
cv2.imshow("MediaPipe Hands", cv2.flip(output_rgb_image, 1))
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()