Spaces:
Sleeping
Sleeping
File size: 6,686 Bytes
84930c3 2d8f4ee b850246 3ca982b 2d8f4ee 84930c3 b850246 5ab41ce b850246 3ca982b b850246 3ca982b b850246 3ca982b b850246 3ca982b b850246 3ca982b b850246 3ca982b 021f396 3ca982b 021f396 3ca982b b850246 |
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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
import os
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"
os.environ["STREAMLIT_CACHE_DIR"] = "/tmp/.streamlit/cache"
os.makedirs("/tmp/.streamlit/cache", exist_ok=True)
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st
import cv2
import mediapipe as mp
import time
from mediapipe.python.solutions import hands
from streamlit_webrtc import webrtc_streamer, VideoTransformerBase
st.set_page_config(page_title="ποΈ Hand Tracking Demo", layout="wide")
# Define constants and helper functions
HAND_CONNECTIONS = hands.HAND_CONNECTIONS
def draw_hand_landmarks(image, hand_landmarks):
h, w, _ = image.shape
# Draw landmarks and connections
# Manually draw landmarks as circles
for idx, landmark in enumerate(hand_landmarks):
cx, cy = int(landmark.x * w), int(landmark.y * h)
cv2.circle(image, (cx, cy), 5, (0, 255, 0), -1) # green dots
# Draw connections (using standard hand skeleton connections)
# Define connections between landmarks as per Mediapipe Hands
connections = HAND_CONNECTIONS
for connection in connections:
start_idx, end_idx = connection
start = hand_landmarks[start_idx]
end = hand_landmarks[end_idx]
start_point = (int(start.x * w), int(start.y * h))
end_point = (int(end.x * w), int(end.y * h))
cv2.line(image, start_point, end_point, (255, 0, 0), 2) # blue lines
BaseOptions = mp.tasks.BaseOptions
HandLandmarker = mp.tasks.vision.HandLandmarker
HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode
model_path = "/app/src/hand_landmarker.task"
options = HandLandmarkerOptions(
base_options=BaseOptions(model_asset_path=model_path),
running_mode=VisionRunningMode.IMAGE,
num_hands=2,
)
landmarker = HandLandmarker.create_from_options(options)
# Set up Streamlit interface
st.title("ποΈ Hand Tracking Demo")
# Add a stop button
stop_button = st.button("Stop")
frame_placeholder = st.empty()
finger_count_text = st.empty()
class VideoProcessor(VideoTransformerBase):
def __init__(self):
self.finger_count = 0
def transform(self, frame):
img = frame.to_ndarray(format="bgr24")
frame_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame_rgb)
result = landmarker.detect(mp_image)
self.finger_count = 0
if result.hand_landmarks:
for hand_landmarks in result.hand_landmarks:
draw_hand_landmarks(img, hand_landmarks)
hand_finger_count = 0
if hand_landmarks[4].y < hand_landmarks[3].y:
hand_finger_count += 1
for i in [8, 12, 16, 20]:
if hand_landmarks[i].y < hand_landmarks[i - 2].y:
hand_finger_count += 1
self.finger_count += hand_finger_count
return img
# Start webcam capture
ctx = webrtc_streamer(
key="hand-tracker",
video_processor_factory=VideoProcessor,
media_stream_constraints={"video": True, "audio": False},
async_processing=True,
rtc_configuration={
"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]
}
)
# Display finger count
if ctx.state.playing:
st.markdown("### Live tracking active...")
while ctx.video_processor:
finger_count_text.markdown(f"### Fingers detected: {ctx.video_processor.finger_count}")
time.sleep(0.1)
else:
st.info("Click 'Start' to begin camera tracking.")
# Initialize finger count
# current_finger_count = 0
# # Initialize MediaPipe Hands
# with hands.Hands(
# max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5
# ) as hands_model:
# while not stop_button:
# ret, frame = cap.read()
# if not ret:
# st.error("Failed to capture video from webcam")
# break
# frame = cv2.flip(frame, 1)
# frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame_rgb)
# result = landmarker.detect(mp_image)
# # Reset finger count for each frame
# current_finger_count = 0
# if result.hand_landmarks:
# for hand_landmarks in result.hand_landmarks:
# # Draw landmarks & connections
# draw_hand_landmarks(frame, hand_landmarks)
# # Calculate finger count for this hand
# hand_finger_count = 0
# if hand_landmarks[4].y < hand_landmarks[3].y: # Thumb
# hand_finger_count += 1
# for i in [8, 12, 16, 20]: # Index, middle, ring, pinky
# if hand_landmarks[i].y < hand_landmarks[i - 2].y:
# hand_finger_count += 1
# # Add this hand's fingers to the total count
# current_finger_count += hand_finger_count
# # Display finger count
# finger_count_text.markdown(f"### Fingers detected: {current_finger_count}")
# # Convert BGR to RGB for displaying in Streamlit
# frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# frame_placeholder.image(frame_rgb, channels="RGB")
# # Add a small delay to simulate real-time processing
# time.sleep(0.05)
# # Rerun to check if stop button was pressed
# if stop_button:
# break
# # Release resources
# cap.release()
# st.success("Camera released. Application stopped.")
# """
# # Welcome to Streamlit!
# Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
# If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
# forums](https://discuss.streamlit.io).
# In the meantime, below is an example of what you can do with just a few lines of code:
# """
# num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
# num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
# indices = np.linspace(0, 1, num_points)
# theta = 2 * np.pi * num_turns * indices
# radius = indices
# x = radius * np.cos(theta)
# y = radius * np.sin(theta)
# df = pd.DataFrame({
# "x": x,
# "y": y,
# "idx": indices,
# "rand": np.random.randn(num_points),
# })
# st.altair_chart(alt.Chart(df, height=700, width=700)
# .mark_point(filled=True)
# .encode(
# x=alt.X("x", axis=None),
# y=alt.Y("y", axis=None),
# color=alt.Color("idx", legend=None, scale=alt.Scale()),
# size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
# )) |