【OpenCV】Python人脸检测+人脸提取

#!/usr/bin/env python

import numpy as np
import cv2
import cv2.cv as cv
from video import create_capture
from common import clock, draw_str

help_message = '''
USAGE: facedetect.py [--cascade ] [--nested-cascade ] []
'''

def detect(img, cascade):
    rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv.CV_HAAR_SCALE_IMAGE)
    if len(rects) == 0:
        return []
    rects[:,2:] += rects[:,:2]
    return rects

def draw_rects(img, rects, color):
    for x1, y1, x2, y2 in rects:
        cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)

if __name__ == '__main__':
    import sys, getopt
    print help_message

    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', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
    #nested_fn  = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")

    cascade = cv2.CascadeClassifier(cascade_fn)
    #nested = cv2.CascadeClassifier(nested_fn)

    cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')

    while True:
        ret, img = cam.read()
        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))
		
        for x1, y1, x2, y2 in rects:
         #   roi = gray[y1:y2, x1:x2]
         #   vis_roi = vis[y1:y2, x1:x2]
            #print(x1,y1,x2,y2)
            crop = vis[y1:y2,x1:x2]
            cv2.imshow('crop',crop)
          #  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)
        
        if 0xFF & cv2.waitKey(5) == 27:
            break
    cv2.destroyAllWindows()



效果:


【OpenCV】Python人脸检测+人脸提取_第1张图片



上边核心代码就几行,我却弄了半天。一方面是python不熟,想学习一下,还有就是没找到合适的文档,如果用c佳佳就快多了。

吐槽一下:网上搜索的各种人脸识别其实就是人脸检测,都没做到识别那步。这里是人脸检测+人脸提取。之后提取到的图片准备扔到神经网络里去进行人脸识别。只不过遇到电脑问题。我的电脑只有一块110G的固态硬盘,老机子翻新用。结果Docker装不上,Vmware+ubuntu14.0硬盘也基本上就满了,CUDA也装不下。等解决了机器问题再继续弄神经网络吧。。



这个主题下推荐两篇博客讲得比较详细:

http://blog.csdn.net/qingyuanluofeng/article/details/51576498

http://blog.csdn.net/topgun_chenlingyun/article/details/10582641

你可能感兴趣的:(OpenCV)