简体   繁体   中英

OpenCV's Cascade classifier face detect freezing

I've been working on a face detection script that lets you detect multiple faces at once, using OpenCV's (cv2) Haar Cascade Classifier, yet , every time I call this function , the program freezes indefinitely without showing any sign of error, here's the code of my function:

 import cv2
 import cv2.cv
 def detect(img, cascade_fn='haarcascade_frontalface_alt2.xml',
           scaleFactor=1.3, minNeighbors=4, minSize=(20, 20),
           flags=cv.CV_HAAR_SCALE_IMAGE):
    cascade = cv2.CascadeClassifier(cascade_fn)
    faces = list()
    test = True
    while test == True:
        rect = cascade.detectMultiScale(img, scaleFactor=scaleFactor,
                                         minNeighbors=minNeighbors,
                                         minSize=minSize, flags=flags)
        if len(rect) == 0:
            test = False
        else:
            for x1, y1, x2, y2 in rect:
                faces.append(img[y1:y2, x1:x2])
                cv2.rectangle(img, (x1, y1), (x2, y2), color, (0, 0, 0))
    return faces

So please , could anybody point to me the reason I'm facing this error, thanks.

In case detectMultiScale won't find any faces, test is assigned False and the loop ends. If it actually detects faces they get added to the list faces and a rectangle is drawn just as you (presumably) intended.

But test remains True , which means that your loop gets executed again. And since none of its input variables were changed detectMultiScale will detect the same faces and again add them to the list faces . Hence in this case the loop will never end.

You might want to do this:

import cv2
def detect(img, cascade_fn='haarcascade_frontalface_alt2.xml',
       scaleFactor=1.3, minNeighbors=4, minSize=(20, 20),
       flags=cv2.cv.CV_HAAR_SCALE_IMAGE):
    cascade = cv2.CascadeClassifier(cascade_fn)
    faces = list()
    rect = cascade.detectMultiScale(img, scaleFactor=scaleFactor,
                                     minNeighbors=minNeighbors,
                                     minSize=minSize, flags=flags)
    for x1, y1, x2, y2 in rect:
        faces.append(img[y1:y2, x1:x2])
        cv2.rectangle(img, (x1, y1), (x2, y2), color, (0, 0, 0))
    return faces

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM