Created
April 21, 2019 11:37
-
-
Save alonlavian/fa84e7f048e1a6780219d01113716855 to your computer and use it in GitHub Desktop.
find and crop faces in an image using google vision API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def detect_face(face_file, max_results=4): | |
client = vision.ImageAnnotatorClient() | |
content = face_file.read() | |
image = types.Image(content=content) | |
return client.face_detection(image=image, max_results=max_results).face_annotations | |
def crop_faces(image_to_crop, cropped_photos_dir): | |
with open(image_to_crop, 'rb') as image: | |
faces = detect_face(image, 8) | |
im = Image.open(image_to_crop) | |
for idx,face in enumerate(faces): | |
vects = face.fd_bounding_poly.vertices | |
im2 = im.crop([vects[0].x, vects[0].y, | |
vects[2].x - 1, vects[2].y - 1]) | |
original_image_name = os.path.basename(image_to_crop) | |
cropped_image_name = os.fsdecode(os.path.splitext(original_image_name)[0]) + "_face_" +str(idx) +".jpg" | |
cropped_image_path = os.path.join(os.fsencode(cropped_photos_dir),os.fsencode(cropped_image_name)) | |
im2.save(cropped_image_path, 'JPEG') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment