在提取动画角色的面部时,我得到了 UnboundLocalError

While extracting face of animated characters I am getting the UnboundLocalError

这是代码

import cv2
import os
import math 
import requests


tom_xml = requests.get('https://raw.githubusercontent.com/hako/dissertation/master/haar_cascades/tom.xml')
f = open('/content/tom.xml','w')
f.write(tom_xml.text)



def video_to_frames(video, frame_folder):
  cam = cv2.VideoCapture("/content/Dataset/" + video)
  frame_rate = cam.get(5)

  try:        
      if not os.path.exists('/content/' + frame_folder): 
          os.makedirs('/content/' + frame_folder)  
  except OSError: 
      print ('Error: Creating directory of data') 

  currentframe = 0

  while cam.isOpened():
    frame_id = cam.get(1)
    ret,frame = cam.read()

    if (frame_id % math.floor(frame_rate)) == 0:
      name = '/content/' + frame_folder +'/frame' + str(currentframe) + '.jpg'

      faceCascade = cv2.CascadeClassifier('/content/tom.xml')
      faces = faceCascade.detectMultiScale(
          frame,
          scaleFactor=1.10, 
          minNeighbors=20, 
          minSize=(48, 48),
          flags=cv2.CASCADE_SCALE_IMAGE
      )

      for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        roi_color = frame[y:y + h, x:x + w]

      cv2.imwrite('/content/' + frame_folder +'/frame{:d}.jpg'.format(currentframe), roi_color)
      currentframe += 1

    if ret != True:
      cam.release()
      break

  cv2.destroyAllWindows()
  print('Completed')

该代码适用于第一个视频文件, video_to_frames('Train Tom and jerry.mp4', 'data_train') 已完成

但是,它抛出 UnboundLocalError: local variable 'roi_color' referenced before assignment for the second video file

video_to_frames('Test Tom and Jerry.mp4', 'data_test')

    UnboundLocalError                         Traceback (most recent call last)

<ipython-input-5-ef0eb71a5dba> in <module>()
----> 1 video_to_frames('Test Tom and Jerry.mp4', 'data_test')

<ipython-input-4-714f5fe4b084> in video_to_frames(video, frame_folder)
     31         roi_color = frame[y:y + h, x:x + w]
     32 
---> 33       cv2.imwrite('/content/' + frame_folder +'/frame{:d}.jpg'.format(currentframe), roi_color)
     34       currentframe += 1
     35 

UnboundLocalError: local variable 'roi_color' referenced before assignment

也许有is/are傻mistake/mistakes。非常感谢任何类型的帮助,提前致谢

您的面孔列表没有条目,您需要在开始 for 循环之前将 roi_color 设置为某个常量,如下所示:

roi_color = ...  # Because if there are zero faces, the for loop will never run.
for (x, y, w, h) in faces:
  cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  roi_color = frame[y:y + h, x:x + w]

cv2.imwrite('/content/' + frame_folder +'/frame{:d}.jpg'.format(currentframe), roi_color)
currentframe += 1