Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import osimport streamlit as stimport mediapipe as mpimport cv2from streamlit_webrtc import webrtc_streamer, VideoTransformerBaseimport avimport asyncio# Prevent asyncio event loop conflictstry:asyncio.get_event_loop().run_until_complete(asyncio.sleep(0))except RuntimeError:asyncio.set_event_loop(asyncio.new_event_loop())# Initialize MediaPipe Handsmp_hands = mp.solutions.handsmp_drawing = mp.solutions.drawing_utils# Path to the gesture recognizer modelmodel_path = "model/gesture_recognizer.task"if not os.path.exists(model_path):st.error(f"Model file not found at {model_path}. Please upload it to the correct directory.")st.stop()class VideoProcessor(VideoTransformerBase):def __init__(self):# Initialize MediaPipe Handsself.hands = mp_hands.Hands(max_num_hands=2,model_complexity=0,min_detection_confidence=0.5,min_tracking_confidence=0.5,)def recv(self, frame):img = frame.to_ndarray(format="bgr24")img = cv2.flip(img, 1) # Flip for a mirror effectimg_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)# Process the frame for hand landmarksresult = self.hands.process(img_rgb)# Draw hand landmarksif result.multi_hand_landmarks:for hand_landmarks in result.multi_hand_landmarks:mp_drawing.draw_landmarks(img, hand_landmarks, mp_hands.HAND_CONNECTIONS)return av.VideoFrame.from_ndarray(img, format="bgr24")# Streamlit UIst.title("Gesture & Hand Landmark Detection 🚀")st.write("This app uses MediaPipe and Streamlit to detect hand landmarks in real-time.")# WebRTC streamer for live videowebrtc_streamer(key="gesture-detection",video_processor_factory=VideoProcessor,rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},)# Footerst.markdown("""<style>.footer {text-align: center; font-size: 12px; color: grey; margin-top: 20px;}</style><p class="footer">Made with ❤️ using Streamlit & MediaPipe</p>""",unsafe_allow_html=True,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import osimport cv2import streamlit as stimport mediapipe as mpfrom PIL import Image# Initialize MediaPipe Handsmp_hands = mp.solutions.handsmp_drawing = mp.solutions.drawing_utils# Streamlit App Titlest.title("Gesture & Hand Landmark Detection 🚀")st.write("This app uses MediaPipe and OpenCV to detect hand landmarks in real-time from your webcam.")# Start Webcamrun_webcam = st.button("Start Webcam")# MediaPipe Hands configurationhands = mp_hands.Hands(max_num_hands=2,min_detection_confidence=0.5,min_tracking_confidence=0.5,)# Webcam video feedif run_webcam:stframe = st.empty() # Placeholder for video framescap = cv2.VideoCapture(0) # Open the first webcamif not cap.isOpened():st.error("Unable to access the webcam. Please ensure it's connected and accessible.")else:while run_webcam:ret, frame = cap.read()if not ret:st.error("Failed to grab frame from webcam.")break# Convert frame to RGBframe = cv2.flip(frame, 1) # Flip horizontallyframe_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)# Process the frame with MediaPipe Handsresult = hands.process(frame_rgb)# Draw hand landmarksif result.multi_hand_landmarks:for hand_landmarks in result.multi_hand_landmarks:mp_drawing.draw_landmarks(frame,hand_landmarks,mp_hands.HAND_CONNECTIONS,mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4),mp_drawing.DrawingSpec(color=(250, 44, 250), thickness=2, circle_radius=2),)# Convert back to BGR for OpenCV displayframe_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)# Display frame in Streamlitstframe.image(frame_bgr, channels="BGR", use_column_width=True)cap.release()hands.close()st.write("Webcam stopped.")
app.py+50-58