首页 > 解决方案 > 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”

我希望它只检测现有面孔上的眼睛,而不是新面孔上的眼睛。我能做些什么来改进这段代码?

标签: pythondlibopencv-python

解决方案


推荐阅读