Thanks to @StarGeek (relevant Reddit post), I was able to write a small script for this.
To get the environment set up in Python 3 (on a Windows 10 machine using Anaconda), I went through the following steps:
pip install opencv-python
- Download and extract
facedetect
- Rename
facedetect
to facedetect.py
- In the file
facedetect.py
, edit the line
DATA_DIR = '/usr/share/opencv/'
to the proper path. On my Windows 10 it was:
DATA_DIR = 'C:/Anaconda3/Lib/site-packages/cv2/data/'
; if you have Python installed only for the current user, it might look something like
DATA_DIR = '%LOCALAPPDATA%/Programs/Python/Python37/Lib/site-packages/cv2/data/'
'HAAR_FRONTALFACE_ALT2': 'haarcascades/haarcascade_frontalface_alt2.xml'
to
'HAAR_FRONTALFACE_ALT2': 'haarcascade_frontalface_alt2.xml',
- Place the image(s) to be processed into the same directory as
facedetect.py
- Run the following script in that directory:
import cv2
import facedetect
import glob
import os
facedetect.load_cascades(facedetect.DATA_DIR)
for file in glob.glob("*.jpg"):
original = cv2.imread(file)
im, faces = facedetect.face_detect_file(file)
if len(faces):
directory = os.path.splitext(os.path.split(file)[1])[0]
os.mkdir(directory)
for i, (x,y,w,h) in enumerate(faces):
face = original[y:y+h, x:x+w]
cv2.imwrite(os.path.join(directory, "{0:03}.jpg".format(i)), face)
For example, on this image (by Hayden Schiff (IagoQnsi, Wikimedia Commons))

the script produces the following output:
