In [16]:
import face_recognition
from PIL import Image
from PIL import ImageDraw
In [17]:
image = face_recognition.load_image_file('IMG-1.jpg')
face_locations = face_recognition.face_locations(image) #(top, right, bottom, left)
In [24]:
hat_img = Image.open("sortinghat.png")
portrait_im = Image.open('IMG-1.jpg')
for (top, right, bottom, left) in face_locations:
nw = right - left
# We set the hat to be 1.5 larger than the width of the face.
hatWidth = 1.5*nw
hatHeight = bottom - top
# Center the hat on the top of the head.
le = left - (right-left)*0.2
# We resize the hat image to our needs.
hat_img_resized = hat_img.resize((int(hatWidth), int(hatHeight)), Image.ANTIALIAS)
le = int(le)
draw = ImageDraw.Draw(portrait_im)
# We keep the transparency of the svg image.
icon = hat_img_resized.convert("RGBA")
# get the correct size
x, y = icon.size
# Knowing that the head dimensions can be split in 4, we adjust where the hat might
# be placed :)
face_h = bottom - top
quarter = int(0.15*face_h)
portrait_im.paste(icon, (abs(le), top-y+quarter), icon)
#The box argument is either a 2-tuple giving the upper left corner.
del draw
portrait_im.save("image_output.jpg", "JPEG")
In [25]:
portrait_im
Out[25]: