python opencv face detection

来源:互联网 发布:vb.net excel教程 编辑:程序博客网 时间:2024/05/01 08:02

just for fun

error: 

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor ...

http://bbs.csdn.net/topics/390944170

http://blog.sina.com.cn/s/blog_79496d6b0100qy6t.html

尝试安装解码器,没成功,改用 mp4 文件了


following is detect face from static image and store the new image

#!/usr/bin/env python# modified by ***, 2015-06-13import numpy as npimport cv2import timeimport sysimport getoptimport oshelp_message = '''USAGE: staticdetec.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<img_source>]'''def draw_str(dst, (x, y), s):    #cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA)    #cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)    # use CV_AA instead of LINE_AA    cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.CV_AA)    cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.CV_AA)def clock():    return cv2.getTickCount() / cv2.getTickFrequency()def detect(img, cascade):    rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE)    if len(rects) == 0:        return []    rects[:,2:] += rects[:,:2]    return rectsdef draw_rects(img, rects, color):    for x1, y1, x2, y2 in rects:        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)def plot_face_range(source, cascade, nested, sleep=5):    img = cv2.imread(source)    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    gray = cv2.equalizeHist(gray)    t = clock()    rects = detect(gray, cascade)    vis = img.copy()    draw_rects(vis, rects, (0, 255, 0))    if not nested.empty():        for x1, y1, x2, y2 in rects:            roi = gray[y1:y2, x1:x2]            vis_roi = vis[y1:y2, x1:x2]            subrects = detect(roi.copy(), nested)            draw_rects(vis_roi, subrects, (255, 0, 0))    dt = clock() - t    draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))    cv2.imshow('facedetect', vis)    newsource = '.'.join(source.split('.')[:-1]) + '_detect' + '.' + source.split('.')[-1]    cv2.imwrite(newsource, vis)    #if 0xFF & cv2.waitKey(5) == 27:    #    break    time.sleep(sleep)  def main():    print help_message    args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])    args = dict(args)    cascade_fn = args.get('--cascade', "../opencv-3.0.0/data/haarcascades/haarcascade_frontalface_alt.xml")    nested_fn  = args.get('--nested-cascade', "../opencv-3.0.0/data/haarcascades/haarcascade_eye.xml")    cascade = cv2.CascadeClassifier(cascade_fn)    nested = cv2.CascadeClassifier(nested_fn)    imgs = [x for x in os.listdir('.') if x.endswith('jpg') and 'detect' not in x]    for img in imgs:      plot_face_range(img, cascade, nested, sleep=3)    cv2.destroyAllWindows()if __name__ == '__main__': main()


0 0