opencv TypeError: 'int' object is not iterable

opencv TypeError: 'int' object is not iterable

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

当我尝试 运行 这段代码时,程序 运行 成功并打开了相机 window。

但是每当我试图在镜头前露脸时,程序都会以 退出代码 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])

我不知道如何解决这个问题。我正在使用 Python3OpenCV3.3.

终于找到解决办法了。问题是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(gray[y:y + h, x:x + w]) 返回 id 来自 数据库.

的人