import pygame import cv2 import numpy as np # Initialize Pygame pygame.init() screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) clock = pygame.time.Clock() # Initialize OpenCV camera cap = cv2.VideoCapture(0) # 0 for default camera # Face Cascade Classifier for detecting faces face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') def detect_face(frame): gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5) if len(faces) > 0: return faces[0] # Only return the first face found else: return None running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Capture frame-by-frame ret, frame = cap.read() if not ret: break # Flip the frame horizontally for better interaction frame = cv2.flip(frame, 1) # Convert the frame to Pygame surface frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = np.rot90(frame) frame = pygame.surfarray.make_surface(frame) frame = pygame.transform.scale(frame, (screen_width, screen_height)) # Clear the screen screen.fill((0, 0, 0)) # Display the frame screen.blit(frame, (0, 0)) # Detect face and draw rectangle around it face_rect = detect_face(cap.read()[1]) if face_rect is not None: x, y, w, h = face_rect pygame.draw.rect(screen, (255, 0, 0), (x, y, w, h), 2) pygame.display.flip() clock.tick(60) # Release the camera and close Pygame cap.release() pygame.quit()