Created
March 30, 2017 21:04
-
-
Save NicholasMurray/927d49e62d2c4998f553ba5492a0c867 to your computer and use it in GitHub Desktop.
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
import os | |
from PIL import Image, ImageOps, ImageDraw | |
def draw_ellipse(image, bounds, width=1, outline='grey', antialias=4): | |
# Use a single channel image (mode='L') as mask. | |
# The size of the mask can be increased relative to the imput image | |
# to get smoother looking results. | |
mask = Image.new( | |
size=[int(dim * antialias) for dim in image.size], | |
mode='L', color='black') | |
draw = ImageDraw.Draw(mask) | |
# draw outer shape in white (color) and inner shape in black (transparent) | |
for offset, fill in (width/-2.0, 'grey'), (width/2.0, 'black'): | |
left, top = [(value + offset) * antialias for value in bounds[:2]] | |
right, bottom = [(value - offset) * antialias for value in bounds[2:]] | |
draw.ellipse([left, top, right, bottom], fill=fill) | |
# downsample the mask using PIL.Image.LANCZOS | |
# (a high-quality downsampling filter). | |
mask = mask.resize(image.size, Image.LANCZOS) | |
# paste outline color to input image through the mask | |
image.paste(outline, mask=mask) | |
def crop_image_and_draw_elipse(image_path, image_location, image_name): | |
img = Image.open(image_path) | |
width, height = img.size | |
imgCropped = img.crop((0, 0, width, width)) | |
bigsize = (imgCropped.size[0] * 3, imgCropped.size[1] * 3) | |
mask = Image.new('L', bigsize, 0) | |
draw = ImageDraw.Draw(mask) | |
draw.ellipse((0, 0) + bigsize, fill=255) | |
mask = mask.resize(imgCropped.size, Image.ANTIALIAS) | |
imgCropped.putalpha(mask) | |
output = ImageOps.fit(imgCropped, mask.size, centering=(0.5, 0.5)) | |
output.putalpha(mask) | |
offset = 3 | |
ellipse_box = [0 + offset, 0 + offset, width - offset, width - offset] | |
draw_ellipse(output, ellipse_box, width=5, antialias=8) | |
output.save(image_location + '/avatar_' + image_name + '.png') | |
agents_dir = '../agents' | |
agent_images_location_list = [] | |
for root, subdirs, files in os.walk(agents_dir): | |
for file in files: | |
agent_images_location_list.append(root + '/' + file) | |
for images_list_item in agent_images_location_list: | |
head, tail = os.path.split(images_list_item) | |
image_name = tail.rsplit( ".", 1 )[ 0 ] | |
image_location = head | |
crop_image_and_draw_elipse(images_list_item, image_location, image_name) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment