from PIL import Image import streamlit as st import cv2 import numpy as np import os # Create a Streamlit app st.title("Face Detection and Image Capture") Name = st.text_input('Enter Your Name:') # Load the Haar Cascade Classifier for face detection face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Initialize the webcam cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) # Define the directory where images will be saved save_dir = "images" # Function to detect faces and draw rectangles def detect_faces(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5) for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2) return image # Capture an image from the camera image_file = st.camera_input("Take a picture") # Display the captured image and perform face detection if image_file: try: # Convert the image to a valid PIL Image pil_image = Image.open(image_file) # Convert PIL Image to NumPy array image_np = np.array(pil_image) # Read the image using OpenCV image_with_faces = detect_faces(image_np) # Convert the BGR image to RGB rgb_image = cv2.cvtColor(image_with_faces, cv2.COLOR_BGR2RGB) st.image(rgb_image, channels="RGB", use_column_width=True) # Define the path to save the image image_filename = f"{Name}.jpg" image_path = os.path.join(save_dir + image_filename) # Save the image locally in RGB format cv2.imwrite(image_path, cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)) st.success(f"Image saved as {image_path}") except Exception as e: st.error(f"Error saving image: {str(e)}") # Release the webcam when the app is done cap.release()