Using OpenCV detectMultiScale to find my face

空扰寡人 提交于 2019-12-03 07:39:46

I changed your code a little in order to make it run on my pc. When I run is at such I get results

import cv2
import cv2.cv as cv
import getopt, sys

def detect(img, cascade):
    for scale in [float(i)/10 for i in range(11, 15)]:
        for neighbors in range(2,5):
            rects = cascade.detectMultiScale(img, scaleFactor=scale, minNeighbors=neighbors,
                                             minSize=(20, 20), flags=cv2.cv.CV_HAAR_SCALE_IMAGE)

            print 'scale: %s, neighbors: %s, len rects: %d' % (scale, neighbors, len(rects))


def find_face_from_img(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.equalizeHist(gray)
    rects = detect(gray, cascade)


if __name__ == '__main__':

    args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
    try: video_src = video_src[0]
    except: video_src = 0
    args = dict(args)


    cascade_fn = args.get('--cascade', "cascades/haarcascade_frontalface_alt.xml")
    cascade = cv2.CascadeClassifier(cascade_fn)

    c=cv2.VideoCapture(0)
    while(1):
        ret, frame = c.read()
        rects = find_face_from_img(frame)
        if 0xFF & cv2.waitKey(5) == 27:
                break

Output:

scale: 1.2, neighbors: 2, len rects: 1
scale: 1.2, neighbors: 3, len rects: 1
scale: 1.2, neighbors: 4, len rects: 1
scale: 1.3, neighbors: 2, len rects: 1
scale: 1.3, neighbors: 3, len rects: 1
scale: 1.3, neighbors: 4, len rects: 0
scale: 1.4, neighbors: 2, len rects: 1
scale: 1.4, neighbors: 3, len rects: 0
scale: 1.4, neighbors: 4, len rects: 0
scale: 1.1, neighbors: 2, len rects: 1
scale: 1.1, neighbors: 3, len rects: 1
scale: 1.1, neighbors: 4, len rects: 1
scale: 1.2, neighbors: 2, len rects: 1
scale: 1.2, neighbors: 3, len rects: 1
scale: 1.2, neighbors: 4, len rects: 1
scale: 1.3, neighbors: 2, len rects: 1

Some advice: Don't pick your minSize too low ... else every small item which resembles a face will be detected.

I assume you are running through all these parameters to find the ones that are the best. I found out the minNeighors shouldn't be too high, else it won't find any.

Make sure your cascade xml file is linked to correctly. If it doesn't find it, it won't give an error, it will just find no faces.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!