Search code examples
pythonpython-3.xopencvface-recognition

face detection , not face detected


I am trying to do face detection but it does not detect any face.

this is the function I have created for face detection

def faceDetection(test_img):
     gray_img=cv2.cvtColor(test_img,cv2.COLOR_BGR2GRAY)
     face_haar_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
     # haar classifier
     faces=face_haar_cascade.detectMultiScale(gray_img,scaleFactor=1.32,minNeighbors=5)

     return faces,gray_img

this is used in

test_img=cv2.imread('pic.png')
faces_detected,gray_img=fr.faceDetection(test_img)
print("faces_detected:",faces_detected)


for (x,y,w,h) in faces_detected:
    cv2.rectangle(test_img,(x,y),(x+w,y+h),(255,0,0),thickness=5)

resized_img=cv2.resize(test_img,(500,500))
cv2.imshow("face",resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows

but when I run this script it does not show any face detected simply give output this

faces_detected: ()

and no box around image


Solution

  • Try using a different haar cascade. The default one is haarcascade_frontalface_alt.xml

    face_haar_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
    

    Change the scale factor you use for the cascade. If that doesn't work you can also reduce also the number of neighbors to maybe 2.

    faces = face_haar_cascade.detectMultiScale(gray_img, scaleFactor=1.1, minNeighbors=5);
    

    Check the number of faces you found

    print('Faces found: ', len(faces))