Spaces:
Sleeping
Sleeping
| # app.py | |
| import streamlit as st | |
| try: | |
| import cv2 | |
| st.write("OpenCV successfully imported!") | |
| except ImportError as e: | |
| st.error(f"Error importing OpenCV: {e}") | |
| import streamlit as st | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| # Load Haar Cascade | |
| def load_cascade(): | |
| cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') | |
| if cascade.empty(): | |
| raise Exception("Haar Cascade file not loaded!") | |
| return cascade | |
| # Detect faces | |
| def detect_faces(image, face_cascade): | |
| gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
| faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) | |
| for (x, y, w, h) in faces: | |
| cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2) | |
| return image, len(faces) | |
| # Streamlit app | |
| def main(): | |
| st.title("Real-Time Face Detection App") | |
| st.write("Upload an image, and the app will detect faces!") | |
| # Load Haar Cascade | |
| face_cascade = load_cascade() | |
| # File uploader | |
| uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"]) | |
| if uploaded_file is not None: | |
| # Read the image | |
| image = np.array(Image.open(uploaded_file)) | |
| image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
| # Detect faces | |
| result_image, face_count = detect_faces(image, face_cascade) | |
| # Convert BGR to RGB for display | |
| result_image = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB) | |
| # Display the image | |
| st.image(result_image, caption=f"Detected {face_count} face(s).", use_column_width=True) | |
| if __name__ == "__main__": | |
| main() | |