Untitled

 avatar
unknown
plain_text
a year ago
2.9 kB
3
Indexable
import pygame
import math
import cv2
import numpy as np

pygame.init()

# Set up the Pygame screen
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Pupil Tracking")

# Set up the OpenCV webcam
cap = cv2.VideoCapture(2)

# Set up a separate window for face tracking
cv2.namedWindow("Face Tracking")

def update():
    pass

def draw():
    screen.fill((0, 0, 0))

    def draw_eye(eye_x, eye_y, pupil_x, pupil_y):
        pygame.draw.circle(screen, (255, 255, 255), (eye_x, eye_y), 50)
        pygame.draw.circle(screen, (0, 0, 100), (pupil_x, pupil_y), 15)

    # Function to detect faces and return the center of the first detected face
    def detect_face(frame):
        face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
        if len(faces) > 0:
            x, y, w, h = faces[0]
            return (x + w // 2, y + h // 2)
        else:
            return None

    # Function to clamp a value within a specified range
    def clamp(value, minimum, maximum):
        return max(minimum, min(value, maximum))

    # Get the webcam frame
    ret, frame = cap.read()

    if ret:
        # Detect face
        face_position = detect_face(frame)

        if face_position:
            # Convert face position to Pygame coordinates
            face_x, face_y = face_position
            face_x = int(face_x / cap.get(3) * screen.get_width())
            face_y = int(face_y / cap.get(4) * screen.get_height())

            # Pupil limits within the eye
            eye_center_x, eye_center_y = 200, 200
            pupil_limit_radius = 30

            # Calculate pupil position with limits
            pupil_x = clamp(face_x - 50, eye_center_x - pupil_limit_radius, eye_center_x + pupil_limit_radius)
            pupil_y = clamp(face_y, eye_center_y - pupil_limit_radius, eye_center_y + pupil_limit_radius)

            # Draw eyes with pupils following the face
            draw_eye(200, 200, pupil_x, pupil_y)

            # Display face tracking in a separate window
            cv2.circle(frame, (face_x, face_y), 30, (255, 0, 0), 2)
        else:
            # If no face is detected, show a temporary image of the eyes
            draw_eye(200, 200, 200, 200)

        pygame.display.update()

        # Display face tracking in a separate window
        cv2.imshow("Face Tracking", frame)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            cap.release()
            cv2.destroyAllWindows()
            pygame.quit()
            exit()

    draw()

    # Check for key events
    key = cv2.waitKey(1) & 0xFF
    if key == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        pygame.quit()
        exit()
Leave a Comment