cannyest / app.py
srivatsavdamaraju's picture
Create app.py
2b9c40c verified
raw
history blame
1.55 kB
import cv2
import streamlit as st
import numpy as np
from PIL import Image
# Load the pre-trained Haar Cascade face detector
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
def detect_faces(frame):
"""
Detect faces in the frame.
Returns the frame with bounding boxes drawn around detected faces.
"""
# 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")
# Capture the video from the webcam
camera = st.camera_input("Capture a photo")
# Process the webcam image if available
if camera:
# Convert the camera image into a numpy array
img = Image.open(camera)
img_array = np.array(img)
# Convert the image to a format OpenCV can process (BGR)
img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
# Detect faces in the image
result_frame = detect_faces(img_bgr)
# Convert result frame back to RGB (for displaying in Streamlit)
result_frame_rgb = cv2.cvtColor(result_frame, cv2.COLOR_BGR2RGB)
# Display the result in Streamlit
st.image(result_frame_rgb, caption="Detected Faces", use_column_width=True)