Tuesday, 9 March 2021

opencv 8 face detection


green indicates face detected, red indicates eye detected




#main.py
import numpy as np
import cv2

cap = cv2.VideoCapture("assets/fashion.mp4")
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #detectMultiScale (frame, a, b)
    #good value of a is between 1 and 1.5, smaller a = more accurate
    #good value of b is between 3 and 6
    #detect face
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        #select region of face
        roi_gray = gray[y:y + w, x:x + w]
        roi_color = frame[y:y + h, x:x + w]

        #detect eye on the face
        eyes = eye_cascade.detectMultiScale(roi_gray, 1.05, 5)
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 0, 255), 2)

    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

No comments:

Post a Comment