import face_recognition
import os
import PIL
PORTRAIT_EXT = ".png"
OUTPUT_DIR = "Output"
def expand_portrait(startY, endY, expand, maxHeight):
offset = min(startY, int(expand/2))
startY -= offset
expand -= offset
offset = min(maxHeight-endY, expand)
endY += offset
expand -= offset
startY -= min(startY, expand)
return startY, endY
if not os.path.exists(OUTPUT_DIR):
os.mkdir(OUTPUT_DIR)
for portrait_filename in [filename for filename in os.listdir() if filename.endswith(PORTRAIT_EXT)]:
portrait = face_recognition.load_image_file(portrait_filename)
locations = face_recognition.face_locations(portrait)
if not locations:
locations = face_recognition.face_locations(portrait, number_of_times_to_upsample=2, model="cnn")
for index, location in enumerate(locations):
startY, endX, endY, startX = location
startY, endY = expand_portrait(startY, endY, portrait.shape[1]-(endY-startY), portrait.shape[0])
result = portrait[startY:endY, :]
result_filename = portrait_filename if index == 0 else os.path.splitext(portrait_filename)[0] + str(index) + PORTRAIT_EXT
PIL.Image.fromarray(result).save(OUTPUT_DIR + os.sep + result_filename)