opencv/samples/python2/facedetect.py

60 lines
1.9 KiB
Python
Raw Normal View History

2011-07-08 00:14:49 +08:00
import numpy as np
import cv2
import cv2.cv as cv
2011-07-08 00:14:49 +08:00
from video import create_capture
from common import clock, draw_str
2011-07-08 00:14:49 +08:00
2011-07-08 06:33:36 +08:00
help_message = '''
USAGE: facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags = cv.CV_HAAR_SCALE_IMAGE)
2011-07-08 06:33:36 +08:00
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)
2011-07-08 06:33:36 +08:00
2011-07-08 00:14:49 +08:00
if __name__ == '__main__':
import sys, getopt
2011-07-08 06:33:36 +08:00
print help_message
2011-07-08 00:14:49 +08:00
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try: video_src = video_src[0]
except: video_src = 0
2011-07-08 06:33:36 +08:00
args = dict(args)
2011-07-08 00:14:49 +08:00
cascade_fn = args.get('--cascade', "../../data/haarcascades/haarcascade_frontalface_alt.xml")
2011-07-08 06:33:36 +08:00
nested_fn = args.get('--nested-cascade', "../../data/haarcascades/haarcascade_eye.xml")
2011-07-08 00:14:49 +08:00
2011-07-08 06:33:36 +08:00
cascade = cv2.CascadeClassifier(cascade_fn)
nested = cv2.CascadeClassifier(nested_fn)
2011-07-08 00:14:49 +08:00
cam = create_capture(video_src, fallback='synth:bg=../cpp/lena.jpg:noise=0.05')
2011-07-08 00:14:49 +08:00
while True:
ret, img = cam.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
2011-07-08 06:33:36 +08:00
gray = cv2.equalizeHist(gray)
t = clock()
2011-07-08 06:33:36 +08:00
rects = detect(gray, cascade)
vis = img.copy()
2011-07-08 06:33:36 +08:00
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]
subrects = detect(roi.copy(), nested)
draw_rects(vis_roi, subrects, (255, 0, 0))
dt = clock() - t
2011-07-08 06:33:36 +08:00
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
2011-07-08 06:33:36 +08:00
cv2.imshow('facedetect', vis)
2011-07-08 00:14:49 +08:00
if 0xFF & cv2.waitKey(5) == 27:
2011-07-08 00:14:49 +08:00
break