mirror of https://github.com/opencv/opencv.git
Open Source Computer Vision Library
https://opencv.org/
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.7 KiB
53 lines
1.7 KiB
import numpy as np |
|
import cv2, cv |
|
from video import create_capture |
|
|
|
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)) |
|
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 = 'synth:bg=../cpp/lena.jpg:noise=0.05' |
|
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) |
|
|
|
while True: |
|
ret, img = cam.read() |
|
gray = cv2.cvtColor(img, cv.CV_BGR2GRAY) |
|
gray = cv2.equalizeHist(gray) |
|
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] |
|
subrects = detect(roi.copy(), nested) |
|
draw_rects(vis_roi, subrects, (255, 0, 0)) |
|
|
|
cv2.imshow('facedetect', vis) |
|
|
|
if cv2.waitKey(5) == 27: |
|
break |
|
|
|
|