import os import cv2 import streamlit as st from PIL import Image def load_cascade(): # Specify the path to the Haar Cascade XML file cascade_path = 'haarcascade_frontalface_default.xml' # Check if the Haar Cascade file exists if not os.path.exists(cascade_path): raise Exception(f"Haar Cascade file not found at {cascade_path}. Please upload the file.") # Load the Haar Cascade classifier face_cascade = cv2.CascadeClassifier(cascade_path) # Check if the file was successfully loaded if face_cascade.empty(): raise Exception(f"Failed to load Haar Cascade file from {cascade_path}.") return face_cascade def main(): st.title("Face Detection App") # Load Haar Cascade for face detection face_cascade = load_cascade() uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"]) if uploaded_file is not None: # Read the image file image = Image.open(uploaded_file) image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Draw rectangles around faces for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # Convert image back to RGB and display it image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) st.image(image, caption="Processed Image", use_column_width=True) if len(faces) > 0: st.success("Face detection successful!") else: st.warning("No faces detected.") if __name__ == "__main__": main()