【问题标题】:'bool' object not iterable'bool' 对象不可迭代
【发布时间】:2019-02-22 01:38:51
【问题描述】:

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

TypeError: 'bool' 对象不可迭代

请帮忙,提前谢谢

代码如下: 导入单元测试 将cognitive_face 导入为CF 从 PIL 导入 Image、ImageFont、ImageDraw 进口时间 导入简历2 从时间导入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()

【问题讨论】:

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


    【解决方案1】:

    @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】:

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

      【讨论】:

      • 我正在尝试检测视频“1.mp4”中的人脸。不能直接写在CF.face.detect中
      • 但据我了解,'CF.face.detect' 函数接受图像作为参数,并且您正试图在那里传递视频。我不熟悉这个库,但我认为这个概念是从视频中捕获单独的帧。然后检测他们上面的人脸,将捕获的图像传递给函数。
      【解决方案3】:

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

      【讨论】:

      • 我没有尝试过,但是 cv2 已经有一些属性可以用来实现你想要的。您应该将 CV_CAP_PROP_POS_MSEC(以毫秒为单位的视频文件的当前位置)设置为您想要的位置。在你的第一个 cap.read() 之前说 cap.set(cv2.CAP_PROP_POS_MSEC,5000) #。如果你愿意,我会更新我的答案。
      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 2021-08-21
      • 2019-01-27
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多