人脸检测 - 打开简历找不到人脸

问题描述

我正在学习 OpenCV。这是我的代码

import cv2
face_patterns = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
sample_image = cv2.imread('1.jpg')
gray = cv2.cvtColor(sample_image,cv2.COLOR_RGB2GRAY)
faces = face_patterns.detectMultiScale(gray,1.3,5)
print(len(faces))
for (x,y,w,h) in faces:
    cv2.rectangle(sample_image,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imwrite('result.jpg',sample_image)

如果我使用图片 A,我可以得到很多人脸,如果我使用图片 B,我就没有。

我多次更改 detectMultiScale(gray,5) 中的参数,它仍然不起作用。

Picture A

Picture A Result

Picture B no face

解决方法

我认为这更多是 Cv2 模块本身的问题。有比 HAAR CASCADE 更好的模型来检测人脸。 face_recognition 库对于检测和识别人脸也非常有用。它使用 hog 作为默认模型。您也可以使用 cnn 以获得更好的准确性,但检测过程会很慢。

查找更多here

import cv2
import face_recognition as fr

sample_image = fr.load_image_file("1.jpg")
unknown_face_loc = fr.face_locations(sample_image,model="hog")
print(len(unknown_face_loc)) #detected face count
for faceloc in unknown_face_loc:
    y1,x2,y2,x1 = faceloc
    cv2.rectangle(sample_image,(x1,y1),(x2,y2),(0,255),2)

sample_image = sample_image[:,:,::-1] #converting bgr image to rbg
cv2.imwrite("result.jpg",sample_image)
,

代替 -

faces = face_patterns.detectMultiScale(gray,1.3,5)

尝试使用 -

faces = face_patterns.detectMultiScale(blackandwhite,5)

如果在此之后仍然出现问题,请查看我的 face detection 代码。

,

它使用 hog 作为默认模型。您也可以使用 cnn 以获得更好的准确性,但检测过程会很慢。


cascade_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_eye.xml')
cap = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret,frame = cap.read()
    # Our operations on the frame come here
    gray = cv2.cvtColor(frame,0)
    detections = cascade_classifier.detectMultiScale(gray,scaleFactor=1.3,minNeighbors=5)
    if(len(detections) > 0):
        (x,y,w,h) = detections[0]
        frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0),2)

    # for (x,h) in detections:
    #   frame = cv2.rectangle(frame,2)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done,release the capture
cap.release()
cv2.destroyAllWindows()```