detectface / app.py
ravinder2024's picture
Update app.py
11c057b verified
import streamlit as st
import numpy as np
import cv2
from PIL import Image
# Define the face detection function
def detect_faces(image):
image_np = np.array(image)
# Convert the image to grayscale for face detection
gray_image = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
# Load the Haar Cascade Classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# Detect faces
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image_np, (x, y), (x + w, y + h), (255, 0, 0), 5)
return image_np
# Streamlit app setup
st.title("Face Detection using Haar Cascade Classifier in streamlit")
st.write("Upload an image, and the model will detect faces and draw bounding boxes around them.")
# File uploader to upload an image
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Open the image file and convert it into a format that OpenCV can process
image = Image.open(uploaded_file)
# Detect faces in the image
result_image = detect_faces(image)
# Convert the result image from OpenCV format back to PIL format for display
result_image_pil = Image.fromarray(result_image)
# Display the image with detected faces
st.image(result_image_pil, caption="Detected Faces", use_column_width=True)
else:
print("no img")