opencv TypeError:' int'对象不可迭代

时间:2018-04-18 20:10:22

标签: python python-3.x opencv opencv3.3

我正在尝试使用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

1 个答案:

答案 0 :(得分:1)

最后,我得到了解决方案。问题是opencv的版本。此代码适用于 opencv2.4 ,我试图在 opencv3 上运行它。

嗯, opencv3 的最终代码如下:

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= 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()

无需提及变量 conf

rec.predict(灰色[y:y + h,x:x + w])数据库<返回此人的 id /强>