opencv/samples/python/facedetect.py

80 lines
2.2 KiB
Python
Raw Normal View History

2013-03-06 14:41:02 +08:00
#!/usr/bin/env python
2015-12-15 07:33:55 +08:00
'''
face detection using haar cascades
USAGE:
facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
# Python 2/3 compatibility
from __future__ import print_function
2012-10-17 07:18:30 +08:00
import numpy as np
import cv2 as cv
2013-03-06 14:41:02 +08:00
# local modules
2012-10-17 07:18:30 +08:00
from video import create_capture
from common import clock, draw_str
def detect(img, cascade):
2015-12-15 07:33:55 +08:00
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv.CASCADE_SCALE_IMAGE)
2012-10-17 07:18:30 +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:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
2012-10-17 07:18:30 +08:00
def main():
2012-10-17 07:18:30 +08:00
import sys, getopt
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
2013-03-06 14:41:02 +08:00
try:
video_src = video_src[0]
except:
video_src = 0
2012-10-17 07:18:30 +08:00
args = dict(args)
2018-11-14 23:56:21 +08:00
cascade_fn = args.get('--cascade', "data/haarcascades/haarcascade_frontalface_alt.xml")
nested_fn = args.get('--nested-cascade', "data/haarcascades/haarcascade_eye.xml")
2012-10-17 07:18:30 +08:00
2018-10-31 20:48:56 +08:00
cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn))
nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn))
2012-10-17 07:18:30 +08:00
2018-10-31 20:48:56 +08:00
cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('samples/data/lena.jpg')))
2012-10-17 07:18:30 +08:00
while True:
2019-10-16 23:49:33 +08:00
_ret, img = cam.read()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gray = cv.equalizeHist(gray)
2012-10-17 07:18:30 +08:00
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))
2012-10-17 07:18:30 +08:00
dt = clock() - t
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
cv.imshow('facedetect', vis)
2012-10-17 07:18:30 +08:00
if cv.waitKey(5) == 27:
2012-10-17 07:18:30 +08:00
break
print('Done')
if __name__ == '__main__':
print(__doc__)
main()
cv.destroyAllWindows()