abubasith86 commited on
Commit
b850246
·
verified ·
1 Parent(s): f5caf45

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +134 -35
src/streamlit_app.py CHANGED
@@ -2,39 +2,138 @@ import altair as alt
2
  import numpy as np
3
  import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
3
  import pandas as pd
4
  import streamlit as st
5
+ import cv2
6
+ import mediapipe as mp
7
+ import time
8
+ import os
9
+ from mediapipe.python.solutions import hands
10
 
11
+ st.set_page_config(page_title="🖐️ Hand Tracking Demo", layout="wide")
12
+
13
+
14
+ # Define constants and helper functions
15
+ HAND_CONNECTIONS = hands.HAND_CONNECTIONS
16
+
17
+ def draw_hand_landmarks(image, hand_landmarks):
18
+ h, w, _ = image.shape
19
+
20
+ # Draw landmarks and connections
21
+ # Manually draw landmarks as circles
22
+ for idx, landmark in enumerate(hand_landmarks):
23
+ cx, cy = int(landmark.x * w), int(landmark.y * h)
24
+ cv2.circle(image, (cx, cy), 5, (0, 255, 0), -1) # green dots
25
+
26
+ # Draw connections (using standard hand skeleton connections)
27
+ # Define connections between landmarks as per Mediapipe Hands
28
+ connections = HAND_CONNECTIONS
29
+ for connection in connections:
30
+ start_idx, end_idx = connection
31
+ start = hand_landmarks[start_idx]
32
+ end = hand_landmarks[end_idx]
33
+ start_point = (int(start.x * w), int(start.y * h))
34
+ end_point = (int(end.x * w), int(end.y * h))
35
+ cv2.line(image, start_point, end_point, (255, 0, 0), 2) # blue lines
36
+
37
+
38
+ BaseOptions = mp.tasks.BaseOptions
39
+ HandLandmarker = mp.tasks.vision.HandLandmarker
40
+ HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions
41
+ VisionRunningMode = mp.tasks.vision.RunningMode
42
+ model_path = "./models/hand_landmarker.task"
43
+ options = HandLandmarkerOptions(
44
+ base_options=BaseOptions(model_asset_path=model_path),
45
+ running_mode=VisionRunningMode.IMAGE,
46
+ num_hands=2,
47
+ )
48
+ landmarker = HandLandmarker.create_from_options(options)
49
+
50
+
51
+ # Set up Streamlit interface
52
+ st.title("🖐️ Hand Tracking Demo")
53
+ # Add a stop button
54
+ stop_button = st.button("Stop")
55
+ frame_placeholder = st.empty()
56
+ finger_count_text = st.empty()
57
+ # Initialize webcam
58
+ cap = cv2.VideoCapture(0)
59
+ # Initialize finger count
60
+ current_finger_count = 0
61
+
62
+ # Initialize MediaPipe Hands
63
+ with hands.Hands(
64
+ max_num_hands=2, min_detection_confidence=0.5, min_tracking_confidence=0.5
65
+ ) as hands_model:
66
+ while not stop_button:
67
+ ret, frame = cap.read()
68
+ if not ret:
69
+ st.error("Failed to capture video from webcam")
70
+ break
71
+ frame = cv2.flip(frame, 1)
72
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
73
+ mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=frame_rgb)
74
+ result = landmarker.detect(mp_image)
75
+ # Reset finger count for each frame
76
+ current_finger_count = 0
77
+ if result.hand_landmarks:
78
+ for hand_landmarks in result.hand_landmarks:
79
+ # Draw landmarks & connections
80
+ draw_hand_landmarks(frame, hand_landmarks)
81
+ # Calculate finger count for this hand
82
+ hand_finger_count = 0
83
+ if hand_landmarks[4].y < hand_landmarks[3].y: # Thumb
84
+ hand_finger_count += 1
85
+ for i in [8, 12, 16, 20]: # Index, middle, ring, pinky
86
+ if hand_landmarks[i].y < hand_landmarks[i - 2].y:
87
+ hand_finger_count += 1
88
+ # Add this hand's fingers to the total count
89
+ current_finger_count += hand_finger_count
90
+ # Display finger count
91
+ finger_count_text.markdown(f"### Fingers detected: {current_finger_count}")
92
+ # Convert BGR to RGB for displaying in Streamlit
93
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
94
+ frame_placeholder.image(frame_rgb, channels="RGB")
95
+ # Add a small delay to simulate real-time processing
96
+ time.sleep(0.05)
97
+ # Rerun to check if stop button was pressed
98
+ if stop_button:
99
+ break
100
+ # Release resources
101
+ cap.release()
102
+ st.success("Camera released. Application stopped.")
103
+
104
+
105
+ # """
106
+ # # Welcome to Streamlit!
107
+
108
+ # Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
109
+ # If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
110
+ # forums](https://discuss.streamlit.io).
111
+
112
+ # In the meantime, below is an example of what you can do with just a few lines of code:
113
+ # """
114
+
115
+ # num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
116
+ # num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
117
+
118
+ # indices = np.linspace(0, 1, num_points)
119
+ # theta = 2 * np.pi * num_turns * indices
120
+ # radius = indices
121
+
122
+ # x = radius * np.cos(theta)
123
+ # y = radius * np.sin(theta)
124
+
125
+ # df = pd.DataFrame({
126
+ # "x": x,
127
+ # "y": y,
128
+ # "idx": indices,
129
+ # "rand": np.random.randn(num_points),
130
+ # })
131
+
132
+ # st.altair_chart(alt.Chart(df, height=700, width=700)
133
+ # .mark_point(filled=True)
134
+ # .encode(
135
+ # x=alt.X("x", axis=None),
136
+ # y=alt.Y("y", axis=None),
137
+ # color=alt.Color("idx", legend=None, scale=alt.Scale()),
138
+ # size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
139
+ # ))