Spaces:
Runtime error
Runtime error
File size: 2,974 Bytes
02d776b 1eff95f 02d776b c0f17eb 02d776b 1eff95f c0f17eb 1eff95f c0f17eb 0a59620 c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f 0a59620 1eff95f c0f17eb 02d776b 1eff95f c0f17eb 1eff95f c0f17eb 1eff95f c0f17eb 368913f |
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 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import cv2
import mediapipe as mp
import os
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
def process_image(image_path):
"""Run hand detection on a static image."""
image = cv2.imread(image_path)
if image is None:
print(f"β Could not read image: {image_path}")
return
with mp_hands.Hands(static_image_mode=True, max_num_hands=2, min_detection_confidence=0.5) as hands:
results = hands.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
if not results.multi_hand_landmarks:
print("π No hands detected in image.")
else:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(
image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3),
mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2, circle_radius=2)
)
cv2.imshow("π€ Hand Recognition (Image Mode)", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
def process_webcam():
"""Run hand detection using webcam if available."""
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("β οΈ Webcam not detected. Switching to image mode...")
return False
with mp_hands.Hands(
static_image_mode=False,
max_num_hands=2,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
) as hands:
print("π₯ Hand Recognition running. Press ESC to exit.")
while True:
ret, frame = cap.read()
if not ret:
print("β Failed to capture frame.")
break
frame = cv2.flip(frame, 1) # Mirror view
results = hands.process(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(
frame,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3),
mp_drawing.DrawingSpec(color=(255, 255, 255), thickness=2, circle_radius=2)
)
cv2.imshow("π€ Hand Recognition (ESC to exit)", frame)
if cv2.waitKey(5) & 0xFF == 27: # ESC
break
cap.release()
cv2.destroyAllWindows()
return True
if __name__ == "__main__":
print("π Starting MediaPipe Hand Recognition App...")
if not process_webcam():
test_image = "hand_test.jpg"
if not os.path.exists(test_image):
print(f"β οΈ No '{test_image}' found. Please place a hand image in this folder.")
else:
process_image(test_image)
|