我正在使用 LBPH 算法进行人脸检测。收集数据和训练的部分工作正常,但在测试部分出现错误
这是测试代码
import cv2
import numpy as np
import webbrowser
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def face_detector(img, size=0.5):
faces = ()
# Convert image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('Printe1r', gray )
if np.count_nonzero(gray) >= 0:
print("in face detector")
faces = face_classifier.detectMultiScale(gray, 1.3, 5)
if faces is ():
return img, []
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,255),2)
roi = img[y:y+h, x:x+w]
roi = cv2.resize(roi, (200, 200))
return img, roi
# Open Webcam
cap = cv2.VideoCapture(0)
print("WebCam opened")
while True:
ret, frame = cap.read()
cv2.imshow('Printe1rwer', frame )
image, face = face_detector(frame)
cv2.imshow('Printe1aas r', image )
print(face)
try:
print("hell1o")
face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)
print("hello")
# Pass face to prediction model
# "results" comprises of a tuple containing the label and the confidence value
results = model.predict(face)
print("Helo",results)
if results[1] < 500:
print("in results < 500")
confidence = int( 100 * (1 - (results[1])/400) )
display_string = str(confidence) + '% Confident it is User'
cv2.putText(face, display_string, (100, 120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,120,150), 2)
if confidence > 75:
print("in confidence < 75")
cv2.putText(face, "Hey Vimal", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Recognition', face )
webbrowser.open('')
break
else:
print("in else")
cv2.putText(face, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.imshow('Face Recognition', face )
except Exception as e:
print(e)
cv2.putText(frame, "No Face Found", (220, 120) , cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.putText(frame, "Locked", (250, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,255), 2)
cv2.imshow('Face Recognition', frame )
pass
if cv2.waitKey(1) == 13: #13 is the Enter Key
break
cap.release()
cv2.destroyAllWindows()
我得到的错误是:
---------------------------------------------------------------------------
error Traceback (most recent call last)
<ipython-input-1-3a076399e5b1> in <module>
34 ret, frame = cap.read()
35 cv2.imshow('Printe1rwer', frame )
---> 36 image, face = face_detector(frame)
37 cv2.imshow('Printe1aas r', image )
38 print(face)
<ipython-input-1-3a076399e5b1> in face_detector(img, size)
14 if np.count_nonzero(gray) >= 0:
15 print("in face detector")
---> 16 faces = face_classifier.detectMultiScale(gray, 1.3, 5)
17
18 if faces is ():
error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'`
有人可以帮帮我吗?我使用的是 OpenCV 版本 4.2.0 有一件事是人脸检测器函数中的变量 gray 的值始终是一个所有值都为零的 numpy 数组。我已经检查过了,但它总是为零。