cannyest / app.py
srivatsavdamaraju's picture
Update app.py
3bd947f verified
raw
history blame
1.78 kB
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()