Spaces:
No application file
No application file
Create hand.py
Browse files
hand.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from cvzone.HandTrackingModule import HandDetector
|
| 5 |
+
|
| 6 |
+
# Streamlit app title
|
| 7 |
+
st.title("Hand Tracking Drawing App")
|
| 8 |
+
|
| 9 |
+
# Initialize the webcam
|
| 10 |
+
cap = cv2.VideoCapture(0)
|
| 11 |
+
|
| 12 |
+
# Initialize the hand detector
|
| 13 |
+
detector = HandDetector(detectionCon=0.8, maxHands=2)
|
| 14 |
+
|
| 15 |
+
# Streamlit placeholder for the video feed
|
| 16 |
+
video_placeholder = st.empty()
|
| 17 |
+
|
| 18 |
+
# Initialize drawing canvas
|
| 19 |
+
height, width = 500, 800
|
| 20 |
+
background_color = (0, 0, 0)
|
| 21 |
+
img = np.full((height, width, 3), background_color, dtype=np.uint8)
|
| 22 |
+
img_show = img.copy()
|
| 23 |
+
|
| 24 |
+
# Function to draw shapes
|
| 25 |
+
def draw(shape, x1, x2, y1, y2, color, thickness):
|
| 26 |
+
if shape == "line":
|
| 27 |
+
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
|
| 28 |
+
elif shape == "circle":
|
| 29 |
+
cv2.circle(img, ((x2 + x1) // 2, (y2 + y1) // 2), int((np.sqrt((x2 - x1)**2 + (y2 - y1)**2)) / 2), color, thickness)
|
| 30 |
+
elif shape == "rectangle":
|
| 31 |
+
cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness)
|
| 32 |
+
|
| 33 |
+
# Main loop
|
| 34 |
+
while True:
|
| 35 |
+
# Read a frame from the webcam
|
| 36 |
+
success, frame = cap.read()
|
| 37 |
+
if not success:
|
| 38 |
+
st.error("Failed to capture video from the webcam.")
|
| 39 |
+
break
|
| 40 |
+
|
| 41 |
+
# Detect hands in the frame
|
| 42 |
+
hands, frame = detector.findHands(frame)
|
| 43 |
+
|
| 44 |
+
# Display the frame in the Streamlit app
|
| 45 |
+
video_placeholder.image(frame, channels="BGR", use_column_width=True)
|
| 46 |
+
|
| 47 |
+
# Check for hand gestures and draw on the canvas
|
| 48 |
+
if hands:
|
| 49 |
+
# Example: Draw a line if two fingers are detected
|
| 50 |
+
if len(hands) == 2:
|
| 51 |
+
x1, y1 = hands[0]['center']
|
| 52 |
+
x2, y2 = hands[1]['center']
|
| 53 |
+
draw("line", x1, x2, y1, y2, (0, 255, 0), 5)
|
| 54 |
+
|
| 55 |
+
# Display the drawing canvas
|
| 56 |
+
st.image(img, channels="BGR", use_column_width=True)
|
| 57 |
+
|
| 58 |
+
# Release the webcam
|
| 59 |
+
cap.release()
|