I wrote the script by looking at this website and it works perfectly but the only problem when I run it on my computer is it only detects the eye region. https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/
Below is the script I wrote based on the website.
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
image = cv2.imread('frame119.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
do I need to add an additional line to fix the problem? Also, the image is in 680x480 dimension, I think that maybe one of the reason why it only detects eye region of the image but I do not have any idea regarding that.
Thank you for the help.
It is not possible to detect eyes if no face is detected .
so try these modification
import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
image = cv2.imread('frame119.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print len(faces) # it will print no of faces detected
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = image[y:y+h, x:x+w]
cv2.imshow('face',roi_color) # It will show a cropped face , if face is detected
cv2.waitKey()
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()