python - UnboundLocalError 当两个面出现在输入
问题描述
def face_detect(img):
hog_rects = hog_detector(img, 0)
hog_faces = np.zeros((0, 4), dtype=int)
for (i, rect) in enumerate(hog_rects):
(x, y, w, h) = rect_to_bb(rect)
face = np.asarray((x, y, w, h), dtype=int)
hog_faces = np.append(hog_faces, [face], axis=0)
return hog_faces
def detect(img, cascade, minimumFeatureSize=(20, 20)):
if cascade.empty():
raise (Exception("There was a problem loading your Haar Cascade xml file."))
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=1, minSize=minimumFeatureSize)
if len(rects) == 0:
return []
rects[:, 2:] += rects[:, :2] # convert last coord from (width,height) to (maxX, maxY)
return rects
def eye_detect(faces, gray, minEyeSize):
# eyes = np.zeros((0, 4), dtype=int)
for (x, y, w, h) in faces:
roi_gray = gray[y:h, x:w]
detected_eyes = detect(roi_gray, haarEyeCascade, minEyeSize)
eyeFix = detected_eyes + [x, y, x, y]
# eyes = np.append(eyes, eyeFix, axis=0)
return eyeFix
我将上述函数用于 dlib_face 检测器,并使用 OpenCV haar eyecascade 使用 eye_detect 函数循环检测到的人脸以查找眼睛。输入是来自 OpenCV 的 VideoCapture 输入。所有函数的输出是一个 numpy 数组,其中包含检测到的特征的 min x、min y max x、max y。
如果只有一张脸,则代码可以正常工作。但是一旦第二张脸出现,它就会抛出
UnboundLocalError:分配前引用的局部变量“eyeFix”
我希望它只检测现有面孔上的眼睛,而不是新面孔上的眼睛。我能做些什么来改进这段代码?
解决方案
推荐阅读
- c# - 检查控制台输出的每个值
- html - 隐藏侧边栏动画后如何执行代码?
- lambda - Java8 Lambda 和流:
而不是必需的 - php - 在 Eloquent ORM 中设置 PDO::ERRMODE_SILENT
- html - Favicon 未出现在浏览器选项卡中
- vba - VBA 将工作表复制到另一个打开的工作簿
- google-api - 如何从后端访问用户 Google Fit 数据
- java - 如何为sql使用准备好的语句?
- java - spring data jpa 生成的存储库方法 findAll 与示例可分页和泛型投影
- node.js - 限制 Nodejs 模块请求的速率