'布尔'对象不可迭代

时间:2018-09-18 05:22:17

标签: python-3.x opencv3.0 face-api

我正在使用python3,opencv 3.4并使用Microsoft Azure的FaceAPI函数'CF.face.detect()' 据我所知,“ for循环”需要可迭代的对象在列表上运行,但是简单的布尔值不是可迭代的。虽然'res1'是一个列表,但我收到此错误。

TypeError:“ bool”对象不可迭代

请帮助,在此先感谢

这是代码:     导入单元测试     导入ognitive_face作为CF     从PIL导入Image,ImageFont,ImageDraw     导入时间     导入cv2     从进口strftime开始

CF.Key.set('') 
#print(CF.Key.get()) 
CF.BaseUrl.set('https://southeastasia.api.cognitive.microsoft.com/face/v1.0/')
#print(CF.BaseUrl.get())
"""Setup Person and Person Group related data."""
person_group_id = '' #id from training terminal
"""Unittest for `face.detect`."""

cap = cv2.VideoCapture('1.mp4') 
while(cap.isOpened()): 
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    print("\n\n ##########.... LOOKING FOR FACES ....##########  \n\n")
    res1 = []
    print(type(res1))
    res1 = CF.face.detect(cap)

    print('\n This is the res1:  ', res1) 
    c = len(res1)
    print('\nTOTAL FACES FOUND:', c) 

    detect_id = [] ##error was here so put exception
    for i in range(c):
        print("\n\n ##########.... DETECTING FACES ....##########  \n\n")
        print('\n This is i in range c', i, c)
        detect_id.append(res1[i]['faceId'])
        #print('\n\n detected faces id ', detect_id[i])

        width  = res1[i]['faceRectangle']['width'] 
        height = res1[i]['faceRectangle']['height']
        x      = res1[i]['faceRectangle']['left']
        y      = res1[i]['faceRectangle']['top']
################## IF ENDS #########################################################################
cv2.imshow('image',img)
    k = cv2.waitKey(100) & 0xff
    if k == 27:
            break
################ WHILE ENDS ####################################
cap.release()
cv2.destroyAllWindows()

3 个答案:

答案 0 :(得分:0)

您应该在捕获的图像上使用CF.face.detect而不是在cap变量上使用吗?

答案 1 :(得分:0)

@Jonasz是正确的,您应该在mp4文件的帧中检测图像上的人脸。

方法CF.face.detect需要一个URI,因此在以下代码中,我们将其写入磁盘之前,将其传递到CF.face.detect

cap = cv2.VideoCapture('1.mp4') 
count = 0  # <--
while(cap.isOpened()): 
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    filename = "frame%d.jpg" % count  # <--
    cv2.imwrite(filename, img)  # <--
    count+=1  # <--

    print("\n\n ##########.... LOOKING FOR FACES ....##########  \n\n")
    res1 = []
    print(type(res1))
    res1 = CF.face.detect(filename)  # <--

答案 2 :(得分:0)

@delephin哦,行得通!但我希望CF.face.detect()在5秒后的任何帧上都能工作。请看,这是我的完整代码:

import unittest
import cognitive_face as CF
from PIL import Image, ImageFont, ImageDraw
import time
import cv2
from time import strftime

CF.Key.set('')  
CF.BaseUrl.set('https://southeastasia.api.cognitive.microsoft.com/face/v1.0/')
person_group_id = '' 

cap = cv2.VideoCapture('emma.mp4') 
count = 0

while(cap.isOpened()): 
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    filename = "frame%d.jpg" % count
    cv2.imwrite(filename, img)
    count+=1 

    S1 = int(strftime("%S"))
    millis = int(round(time.time() * 1000))          
    previous_millis = 0
    interval = 5000000

    if(int(millis-previous_millis) >= interval): 
        previous_millis = millis
        print("\n\n ##########.... LOOKING FOR FACES ....##########  \n\n")

        res1 = CF.face.detect(filename) 
        print('\n This is the res1:  ', res1) 
        c = len(res1)
        print('\nTOTAL FACES FOUND:', c) 

        try:
            detect_id = [] ##error was here so put exception
            for i in range(c):
                print("\n\n ##########.... DETECTING FACES ....##########  \n\n")
                print('\n This is i in range c', i, c)
                detect_id.append(res1[i]['faceId'])
                #print('\n\n detected faces id ', detect_id[i])

                width  = res1[i]['faceRectangle']['width'] 
                height = res1[i]['faceRectangle']['height']
                x      = res1[i]['faceRectangle']['left']
                y      = res1[i]['faceRectangle']['top']

    ######################## IDENTIFICATION ##########################################################################
                print("\n\n ###########.... IDENTIFYING FACES....############# \n\n")
                res2 = CF.face.identify( [detect_id[i]], person_group_id = person_group_id)###big error

                try:
                    recognized_id = res2[0]['candidates'][0]['personId'] 
                    res3 = CF.person.get(person_group_id, recognized_id )
                    #print('Identified person{0}: ', res3) 
                    name = res3['name']
                    print('\nThe image is of Detected person is: ', name)

                    im = Image.open(image) 
                    dr = ImageDraw.Draw(im)

                    dr.rectangle(((x,y),(x+width,y+height)), outline = "blue")
                    font = ImageFont.truetype("/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-M.ttf", 16)
                    dr.text((x, y),name,(255,255,255),font=font)

                    im.show(im)
                    time.sleep(5)

                except:
                    print ('\nPerson is not Trained !!' )
        except: 
            c = 0
            print('Face count is:', c, "No Face Found") 
################## IF ENDS ######################################################################################
    cv2.imshow('image',img)
    k = cv2.waitKey(100) & 0xff
    if k == 27:
            break
################ WHILE ENDS ###############################################################################
cap.release()
cv2.destroyAllWindows()