Skip to content

Instantly share code, notes, and snippets.

@Choumingzhao
Last active September 5, 2017 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Choumingzhao/2580cc8e3270efebaef8dd29958e1cd8 to your computer and use it in GitHub Desktop.
Save Choumingzhao/2580cc8e3270efebaef8dd29958e1cd8 to your computer and use it in GitHub Desktop.
将多个静态图片转换为GIF文件并添加说明文字

有时候你需要用多个相同尺寸的静态图片转换为一个gif文件,这个时候你需要使用的Python库是imageio

使用$ pip install imageio可以安装。   使用static_images_to_gif.py 中的代码可以快速将具有相同命名特征的文件排序后组合成gif,你可以在理解其内容后作出相应更改才可运行。

同时新的问题出现了,如果我们想给每个图片添加不同的字体然后再做成gif呢? 这个时候还是要使用pillow。前面iamgeio已经安装了pillow。详见combine_multiple_images_and_add_caption.py。此处我们采用的方法新建一个空白的比原照片尺寸稍大的图片,添加文字之后在将原图粘贴上去。

参考:

  1. Programmatically generate video or animated GIF in Python?
  2. Add caption to image using Pillow
  3. paste one image to another using Pillow
import imageio
from glob import glob
l = glob('train_*_0099.png') # choose image file with this name format
ll = sorted(l, key=lambda s: int(s.replace('train_', '').replace('_0099.png', ''))) # sort the image with number order
for img in ll[::5]: # when files are too many to put in one file, only choose several of them
images.append(imageio.imread(img))
imageio.mimsave('../test.gif', images, duration=0.3) # store the file in parent directory
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment