Skip to content

Instantly share code, notes, and snippets.

@ma1onso
Last active December 4, 2017 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ma1onso/449963f72c9cf153855422146bfb5d2e to your computer and use it in GitHub Desktop.
Save ma1onso/449963f72c9cf153855422146bfb5d2e to your computer and use it in GitHub Desktop.
Count faces
from cv2 import imread, cvtColor, CascadeClassifier, COLOR_BGR2GRAY, CASCADE_SCALE_IMAGE
HAARCASCADE_FRONTALFACE = '{base_path}/cascades/haarcascade_frontalface_default.xml'.format(
base_path=os.path.abspath(os.path.dirname(__file__).replace('configs', ''))
)
num_faces = 0
locations = []
image = imread ('PATH/TO/IMAGE')
gray = cvtColor(image, COLOR_BGR2GRAY)
detector = CascadeClassifier(HAARCASCADE_FRONTALFACE)
rects = detector.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=CASCADE_SCALE_IMAGE
)
locations = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects]
num_faces = len(rects)
return {'success': True, 'num_faces': num_faces, 'locations': locations}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment