Pi 5 face detection
from picamera2 import Picamera2, Preview import cv2 import time # Initialize the camera picam2 = Picamera2() camera_config = picam2.create_preview_configuration(main={"size": (640, 480)}) picam2.configure(camera_config) picam2.start() # Allow the camera to warm up time.sleep(2) while True: # Capture the image frame = picam2.capture_array() # Convert the frame from RGB to BGR frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # Convert the frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Load the pre-trained face detection model face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Detect faces faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Draw rectangles around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2) # Display the resulting frame cv2.imshow('Face Detection', frame) # Break the loop if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # Stop the camera and close the window picam2.stop() cv2.destroyAllWindows()
Leave a Comment