|
import imageio |
|
import os |
|
|
|
from glob import glob |
|
from PIL import Image, ImageDraw, ImageFont |
|
|
|
def add_caption(src, caption='', dst='.'): |
|
"""Add caption for image file *src* and save it in directory dst. |
|
""" |
|
base = Image.open(src).convert('RGBA') # base.size = (384, 384) # read PNG files with 4 channels |
|
txt = Image.new('RGBA', (base.size[0], base.size[1]+40), (0, 0, 0, 0)) # the text layer a bit larger than the original |
|
fnt = ImageFont.truetype('arial.ttf', 30) # speficy the typeface and fontsize, this *arial.ttf* works well on windows |
|
d = ImageDraw.Draw(txt) |
|
d.text((130, 380), "{}".format(caption), font=fnt, fill=(255, 255, 0, 255)) # set position, centent, filled-color of text |
|
txt.paste(base) # paste the smaller image to larger image |
|
|
|
filename = os.path.basename(src) |
|
dst_file = os.path.join(dst, filename) |
|
txt.save(dst_file) |
|
return dst_file |
|
|
|
DIRNAME = "extracted" |
|
|
|
if not os.path.exists(DIRNAME): |
|
os.mkdir(DIRNAME) |
|
|
|
get_number = lambda s: int(s.replace('train_', '').replace('_0799.png', '')) # extract number from file name |
|
l = glob('train_*_0799.png') # choose image file with this name format |
|
|
|
ll = sorted(l, key=get_number) # sort the image with number order |
|
images = [] |
|
for img in ll[::]: # when files are too many to put in one file, only choose several of them |
|
images.append(imageio.imread(add_caption(img, caption="epoch {}".format(get_number(img)), dst=DIRNAME))) |
|
imageio.mimsave('{}/output.gif'.format(DIRNAME), images, duration=0.3) # store the file in parent directory |