Spaces:
Sleeping
Sleeping
File size: 1,781 Bytes
2b9c40c 3bd947f 2b9c40c 3bd947f 2b9c40c 3bd947f 2b9c40c 3bd947f 2b9c40c 3bd947f 2b9c40c 3bd947f 2b9c40c 3bd947f |
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 |
import cv2
import streamlit as st
import numpy as np
from PIL import Image
import time
# Load the pre-trained Haar Cascade face detector
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Define a function to detect faces in a frame
def detect_faces(frame):
# Convert the frame to grayscale (Haar Cascade works on grayscale images)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
return frame
# Streamlit UI for the app
st.title("Real-Time Face Detection")
# Create a container for the webcam video feed
video_placeholder = st.empty()
# Start the webcam feed
cap = cv2.VideoCapture(0) # 0 is the default webcam device
if not cap.isOpened():
st.error("Error: Could not access the webcam.")
else:
# Start capturing video frames
while True:
ret, frame = cap.read()
if not ret:
st.error("Failed to grab frame.")
break
# Detect faces in the current frame
result_frame = detect_faces(frame)
# Convert BGR (OpenCV format) to RGB (for Streamlit display)
result_frame_rgb = cv2.cvtColor(result_frame, cv2.COLOR_BGR2RGB)
# Display the frame in Streamlit (dynamically updating the image)
video_placeholder.image(result_frame_rgb, channels="RGB", use_column_width=True)
# Add a small delay to control the frame rate (optional)
time.sleep(0.03) # This gives roughly 30 FPS
# Release the webcam when the stream ends
cap.release()
|