如何解决通过这段代码,我想收集脸部样本,但它给了错误
import cv2
import numpy
face_classifier = cv2.CascadeClassifier('C:/Users/my pc/AppData/Local/Programs/Python/python38/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
def face_extractor(img): # to extract face feature
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces= face_classifier.detectMultiScale(gray,1,3,5)
if faces is():
#if there is no face on screen
return None
for(x,y,w,h) in faces: # if face present,crop face,return it
cropped_face = img[y:y+h,x:x+w]
return cropped_face
cap= cv2.VideoCapture(0,cv2.CAP_DSHOW) # to open camera
count = 0
while True:
ret,frame = cap.read()
if face_extractor(frame) is not None:
count += 1
face = cv2.resize(face_extractor(frame),(200,200))
face = cv2.cvtColor(face,cv2.COLOR_BGR2GRAY)
file_name_path = 'C:/Users/my pc/faces/user' + str(count)+'.jpg'
cv2.imwrite(file_name_path,face)
cv2.putText(face,str(count),(50,50),cv2.FONT_HERShey_COMPLEX,(0,255,0),2) #count how mnay pics clicked
cv2.imshow('face cropper',face)
else:
print('face not found')
pass
if cv2.waitKey1 == 13 or count == 100:
break
cap.release()
cv2.destroyAllWindows()
print('collecting samples complete')
以下是错误
ace.py:9: SyntaxWarning: "is" with a literal. Did you mean "=="?
if faces is():
Traceback (most recent call last):
File "face.py",line 24,in <module>
if face_extractor(frame) is not None:
File "face.py",line 7,in face_extractor
faces= face_classifier.detectMultiScale(gray,5)
cv2.error: OpenCV(4.4.0) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-j8nxabm_\opencv\modules\objdetect\src\cascadedetect.cpp:1689: error: (-215:Assertion Failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'
解决方法
错误消息显示if faces is():
有问题,因为Python中没有is()
。
detectMultiScale()
提供带有对象的列表,您可以检查此列表是否为空:
if len(faces) == 0:
return None
或更易读
if not faces:
return None
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。