我正在尝试使用 OpenCV 检测人脸。我有一个文件识别器.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。