Created
November 3, 2014 16:50
-
-
Save linuxlizard/8bff90c5ad233c2ef0f7 to your computer and use it in GitHub Desktop.
Fix Halloween photos with Python PIL and multiprocessing
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
#!/usr/bin/env python3 | |
# Fix Halloween photobooth photos | |
# (Also an excuse to play with thread pools some more) | |
# | |
# http://pillow.readthedocs.org/en/latest/index.html | |
# https://medium.com/@thechriskiehl/parallelism-in-one-line-40e9b2b36148 | |
# | |
# davep 03-Nov-2014 | |
import sys | |
import os | |
import PIL | |
from PIL import Image | |
from multiprocessing.dummy import Pool as ThreadPool | |
def get_file_list(): | |
# get all jpeg files | |
return [ f for f in os.listdir(".") if "29_Oct_" in f and f.endswith(".jpg") ] | |
def fix_filename(filename_in): | |
# filename looks like: | |
# trunk_or_treat_29_Oct_2014_21_04.jpg | |
# | |
# The clock on the Pi was wrong. So fix the filename to reflect proper | |
# date/time. 29_Oct_2014_22_04 -> 31_Oct_2014_17_04 (best guess subtract | |
# five hours from the time) | |
fields = filename_in.split("_") | |
# ['trunk', 'or', 'treat', '29', 'Oct', '2014', '22', '05.jpg'] | |
day_idx = 3 | |
hour_idx = 6 | |
hour_offset = 5 | |
new_day = '31' | |
new_hour = str(int(fields[hour_idx])-hour_offset) | |
fields[day_idx] = new_day | |
fields[hour_idx] = new_hour | |
new_filename = "_".join(fields) | |
return new_filename | |
def make_thumbnail_filename(filename): | |
filename_thumb,ext = os.path.splitext(filename_in) | |
filename_thumb += "_thumb.jpg" | |
return filename_thumb | |
def process_image(arg): | |
# must rotate the images -π/4 (I rotated them in the Raspberry Pi code for | |
# printing) and make a thumbnail | |
filename_in, filename_out = arg | |
print("{0} -> {1}".format(filename_in,filename_out) ) | |
img = Image.open(filename_in) | |
img.load() | |
# rotate | |
img_rot = img.rotate(270) | |
img_rot.save(filename_out) | |
# make thumbnail | |
filename_thumb = make_thumbnail_filename(filename_out) | |
img_rot.thumbnail((128,128),Image.ANTIALIAS) | |
img_rot.save(filename_thumb) | |
def main() : | |
files_in = get_file_list() | |
files_out = [ fix_filename(f) for f in files_in ] | |
pool = ThreadPool(4) | |
results = pool.map(process_image,zip(files_in,files_out)) | |
pool.close() | |
pool.join() | |
if __name__=='__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment