Learn Before
Concept
Face and Eye Detection
OpenCV has pre-trained classifiers that will be able to look through the image and search for features common to eyes and faces.
cap = cv2.VideoCapture(0) face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'hararcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'hararcascade_eye.xml') while True: ret, frame = cap.read() #convert to gray scale, cascades require gray scale cv2.cvtColor(frame, cv2.COLOR_BGR_2_GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 5) roi_gray = gray[y:y+w, x:x+w] roi_color = frame[y:y+h, x:x+w] eyes = eye_cascade.detectMultiScale(roi_gray, 1.3, 5) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 5) cv2.imshow('frame', frame) if cv2.waitKey(1) == ord('q'): break cap.release() cv2.destroyAllWindows()
Since the cascades were trained on certain sized images, i.e. 400x400 and may not be able to work on an image file that is 10000x10000. Changing the scale factor will allow for a speed/accuracy trade off. Closer to 1 values will slow down but more accurate.
minNeighbors is an accuracy specification. How many different features must we detect before we can label it as a face / eye.
minSize and maxSize are just optional parameters for if you know how big faces are in the images. detectMultiScale(base image, scale factor, minNeighbors, minSize, maxSize)
0
1
Updated 2021-07-13
Tags
Python Programming Language
Data Science