Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import streamlit as st
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
# Load the pre-trained Haar Cascade face detector
|
7 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
8 |
+
|
9 |
+
def detect_faces(frame):
|
10 |
+
"""
|
11 |
+
Detect faces in the frame.
|
12 |
+
Returns the frame with bounding boxes drawn around detected faces.
|
13 |
+
"""
|
14 |
+
# Convert the frame to grayscale (Haar Cascade works on grayscale images)
|
15 |
+
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
16 |
+
|
17 |
+
# Detect faces in the image
|
18 |
+
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
|
19 |
+
|
20 |
+
# Draw rectangles around the faces
|
21 |
+
for (x, y, w, h) in faces:
|
22 |
+
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
|
23 |
+
|
24 |
+
return frame
|
25 |
+
|
26 |
+
# Streamlit UI for the app
|
27 |
+
st.title("Real-Time Face Detection")
|
28 |
+
|
29 |
+
# Capture the video from the webcam
|
30 |
+
camera = st.camera_input("Capture a photo")
|
31 |
+
|
32 |
+
# Process the webcam image if available
|
33 |
+
if camera:
|
34 |
+
# Convert the camera image into a numpy array
|
35 |
+
img = Image.open(camera)
|
36 |
+
img_array = np.array(img)
|
37 |
+
|
38 |
+
# Convert the image to a format OpenCV can process (BGR)
|
39 |
+
img_bgr = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
|
40 |
+
|
41 |
+
# Detect faces in the image
|
42 |
+
result_frame = detect_faces(img_bgr)
|
43 |
+
|
44 |
+
# Convert result frame back to RGB (for displaying in Streamlit)
|
45 |
+
result_frame_rgb = cv2.cvtColor(result_frame, cv2.COLOR_BGR2RGB)
|
46 |
+
|
47 |
+
# Display the result in Streamlit
|
48 |
+
st.image(result_frame_rgb, caption="Detected Faces", use_column_width=True)
|