我正在尝试使用OpenCV检测人脸。我有一个名为recognizer.py的文件,其内容如下:
import cv2
faceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cam = cv2.VideoCapture(0)
rec = cv2.face.createLBPHFaceRecognizer()
rec.load('recognizer/trainningData.yml')
id = 0
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceDetect.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
id, conf = rec.predict(gray[y:y + h, x:x + w])
cv2.putText(img, str(id), (x, y + h), font, 255, (255, 0, 0))
cv2.imshow("Face", img)
if cv2.waitKey(1) == ord('q'):
break
cam.release()
cv2.destroyAllWindows()
当我尝试运行这段代码时,程序成功运行并打开了一个摄像头窗口。但是每当我试图把我的脸放在摄像头前时,程序会以退出码1终止,并显示以下错误信息:
Traceback (most recent call last):
File "/home/prateek/recognizer.py", line 15, in <module>
id, conf = rec.predict(gray[y:y + h, x:x + w])
TypeError: 'int' object is not iterable
Process finished with exit code 1
意思是,我在第15行遇到了错误,错误如下:
id, conf = rec.predict(gray[y:y + h, x:x + w])
我不知道如何解决这个问题。我正在使用Python3和OpenCV3.3。