spacehands / app.py
drixo's picture
Update app.py
368913f verified
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)