Update app.py
Browse files4 unmodified lines56789101110 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455565758594 unmodified lines6465666768697071727374754 unmodified linesfrom streamlit_webrtc import webrtc_streamer, VideoTransformerBaseimport avfrom queue import Queueimport os# MediaPipe components for gesture recognition and hand landmarksmp_hands = mp.solutions.hands10 unmodified linesif not os.path.exists(model_path):raise FileNotFoundError(f"Model file not found at {model_path}")# Gesture recognizer configurationoptions = GestureRecognizerOptions(base_options=BaseOptions(model_asset_path=model_path),running_mode=VisionRunningMode.LIVE_STREAM)# Custom video processor class for handling webcam inputclass VideoProcessor(VideoTransformerBase):def __init__(self):self.recognizer = GestureRecognizer.create_from_options(options)self.hands = mp_hands.Hands(max_num_hands=2,model_complexity=0,min_detection_confidence=0.3,min_tracking_confidence=0.3)self.gesture_queue = Queue()def recv(self, frame):img = frame.to_ndarray(format="bgr24")img = cv2.flip(img, 1) # Flip the image horizontally for a mirror effectimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# Perform hand landmark detectionhand_results = self.hands.process(img_rgb)# Perform gesture recognitionmp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img_rgb)current_time_ms = int(time.time() * 1000)result = self.recognizer.recognize(mp_image, current_time_ms)# Draw landmarks and recognized gestures on the frameif hand_results.multi_hand_landmarks:for hand_landmarks in hand_results.multi_hand_landmarks:mp_drawing.draw_landmarks(4 unmodified linesmp_drawing_styles.get_default_hand_connections_style())# Display recognized gesturesif result.gestures:for hand_gestures in result.gestures:for gesture in hand_gestures:gesture_text = f"{gesture.category_name} ({gesture.score:.2f})"cv2.putText(img, gesture_text, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)return av.VideoFrame.from_ndarray(img, format="bgr24")4 unmodified lines567891010 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071724 unmodified lines777879808182838485868788899091929394954 unmodified linesfrom streamlit_webrtc import webrtc_streamer, VideoTransformerBaseimport avfrom queue import Queue# MediaPipe components for gesture recognition and hand landmarksmp_hands = mp.solutions.hands10 unmodified linesif not os.path.exists(model_path):raise FileNotFoundError(f"Model file not found at {model_path}")# Custom video processor class for handling webcam inputclass VideoProcessor(VideoTransformerBase):def __init__(self):self.gesture_queue = Queue() # Queue to store gesture results# Configure the Gesture Recognizer with a callbackself.recognizer = GestureRecognizer.create_from_options(GestureRecognizerOptions(base_options=BaseOptions(model_asset_path=model_path),running_mode=VisionRunningMode.LIVE_STREAM,result_callback=self.handle_result, # Set the result callback))self.hands = mp_hands.Hands(max_num_hands=2,model_complexity=0,min_detection_confidence=0.3,min_tracking_confidence=0.3)def handle_result(self, result: GestureRecognizerResult, output_image: mp.Image, timestamp_ms: int):# Process the result and add it to the queuegestures = []if result.gestures:for hand_gestures in result.gestures:for gesture in hand_gestures:gestures.append(f"{gesture.category_name} (Confidence: {gesture.score:.2f})")else:gestures.append("No gestures detected.")self.gesture_queue.put(gestures)def recv(self, frame):img = frame.to_ndarray(format="bgr24")img = cv2.flip(img, 1) # Flip horizontallyimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# Perform hand landmark detectionhand_results = self.hands.process(img_rgb)# Perform gesture recognition asynchronouslymp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img_rgb)current_time_ms = int(time.time() * 1000)self.recognizer.recognize_async(mp_image, current_time_ms)# Draw hand landmarks on the frameif hand_results.multi_hand_landmarks:for hand_landmarks in hand_results.multi_hand_landmarks:mp_drawing.draw_landmarks(4 unmodified linesmp_drawing_styles.get_default_hand_connections_style())# Optionally display detected gestures from the queueif not self.gesture_queue.empty():gestures = self.gesture_queue.get()for i, gesture in enumerate(gestures):cv2.putText(img,gesture,(10, 50 + i * 30),cv2.FONT_HERSHEY_SIMPLEX,1,(0, 255, 0),2,)return av.VideoFrame.from_ndarray(img, format="bgr24")
app.py+39-19