Skip to content

Instantly share code, notes, and snippets.

@gurum9
Created June 27, 2018 04:08
Show Gist options
  • Save gurum9/47122150f9ac6791d6c94fceb3c07a98 to your computer and use it in GitHub Desktop.
Save gurum9/47122150f9ac6791d6c94fceb3c07a98 to your computer and use it in GitHub Desktop.
detectface_2.py
#-*- coding: utf-8 -*-
#!/usr/bin/env python
'''
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
import numpy as np
import cv2 as cv
from pprint import pprint
# local modules
from video import create_capture
from common import clock, draw_str
mosaic_rate = 30
def detect(img, cascade):
rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
flags=cv.CASCADE_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:
cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
if __name__ == '__main__':
import sys, getopt
print(__doc__)
args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
try:
video_src = video_src[1]
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 = cv.CascadeClassifier(cascade_fn)
nested = cv.CascadeClassifier(nested_fn)
cam = create_capture(video_src, fallback='synth:bg=../data/lena.jpg:noise=0.05')
while True:
ret, img = cam.read()
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gray = cv.equalizeHist(gray)
t = clock()
rects = detect(gray, cascade)
vis = img.copy()
for (x, y, w, h) in rects:
# print ("detect face rects : {:d}, {:d}, {:d}, {:d}".format(x,y,w,h))
face_img = img[y:y+h, x:x+w]
face_img = cv.resize(face_img, (w//mosaic_rate, h//mosaic_rate))
face_img = cv.resize(face_img, (w, h), interpolation=cv.INTER_AREA)
vis[y:y+h, x:x+w] = face_img
dt = clock() - t
draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
cv.imshow('facedetect', vis)
if cv.waitKey(5) == 27:
break
cv.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment