File size: 1,588 Bytes
92a9ac2
9dde88d
92a9ac2
 
9dde88d
 
 
92a9ac2
9d900a9
 
 
 
 
 
92a9ac2
9d900a9
 
92a9ac2
9d900a9
 
 
 
92a9ac2
9d900a9
 
 
 
 
92a9ac2
9d900a9
 
 
 
 
92a9ac2
9d900a9
 
 
92a9ac2
9d900a9
 
92a9ac2
9d900a9
 
92a9ac2
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
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)