import streamlit as st import cv2 import numpy as np # Load the Haar Cascade face detector cascade_path = "haarcascade_frontalface_default.xml" detector = cv2.CascadeClassifier(cascade_path) # Check if the cascade file is loaded if detector.empty(): st.error("Error: Could not load Haar Cascade. Ensure the XML file is in the correct location.") else: # Streamlit app title st.title("Face Detection App") # File uploader uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) if uploaded_file is not None: # Convert uploaded file to OpenCV format file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8) image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) if image is None: st.error("Error: Could not process the uploaded image.") else: # Convert image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Perform face detection rects = detector.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) ) st.write(f"Detected {len(rects)} face(s).") # Draw bounding boxes around detected faces for (x, y, w, h) in rects: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # Convert image to RGB for display image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Display the image st.image(image_rgb, caption="Detected Faces", use_column_width=True)