import cv2 import av import asyncio import numpy as np import streamlit as st from streamlit_webrtc import WebRtcMode, webrtc_streamer # Fix asyncio event loop issue on Windows (this is useful for local testing on Windows) if hasattr(asyncio, 'WindowsSelectorEventLoopPolicy'): asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) # Load Haarcascade model face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Face detection function for WebRTC def video_frame_callback(frame: av.VideoFrame) -> av.VideoFrame: # Convert the frame to a numpy array (OpenCV format) img = frame.to_ndarray(format="bgr24") # Convert image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect faces in the grayscale image faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Draw rectangles around detected faces for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # Return the processed frame return av.VideoFrame.from_ndarray(img, format="bgr24") # Streamlit UI st.title("Real-Time Face Detection") st.write("Using OpenCV and Haar Cascade Model") # WebRTC streamer (webrtc_streamer already handles async tasks internally) webrtc_streamer( key="face-detection", mode=WebRtcMode.SENDRECV, rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]}, video_frame_callback=video_frame_callback, async_processing=True # Keep this enabled for async processing )