File size: 1,896 Bytes
63fc05c 1c29168 5cd4282 61a2f93 2db55d1 1c29168 5cd4282 ec72a13 5cd4282 ec72a13 5cd4282 ec72a13 343617d 5fce2a9 343617d 5cd4282 480a0cf 5cd4282 ec72a13 343617d e1d6483 3e1b572 e1d6483 61a2f93 343617d 61a2f93 2bdc39b 480a0cf 343617d 851fa19 343617d 480a0cf 0e14de1 480a0cf 343617d 5cd4282 e1d6483 | 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 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() |