我正在尝试使用png
图像制作gif,并且需要在数据上添加一些信息。我已经发布了代码和下面的图像。而且我不知道发生了什么,为什么它不起作用。文本不会出现在图像上,而是图像的颜色会改变。这很奇怪。我无法弄清楚这有什么问题。
import os
import sys
#import imageio as io
import re
from PIL import Image, ImageDraw, ImageFont
#####################################################################################################
#key to sort the file_names in order
numbers = re.compile(r'(\d+)')
def numericalSort(value):
parts = numbers.split(value)
parts[1::2] = map(int, parts[1::2])
return parts
############################################################
file_names = sorted((fn for fn in os.listdir('.') if fn.startswith('fileName')), key = numericalSort)
######################################################################
def gen_frame(path,time=time, counter=None):
im = Image.open(path)
alpha = im.getchannel('A')
# Convert the image into P mode but only use 255 colors in the palette out of 256
im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
width, height = im.size
print im.size
# Set all pixel values below 128 to 255 , and the rest to 0
mask = Image.eval(alpha, lambda a: 255 if a <=20 else 0)
# Paste the color of index 255 and use alpha as a mask
im.paste(255, mask)
# The transparency index is 255
im.info['transparency'] = 255
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(font = '/usr/share/fonts/truetype/DejaVuSans.ttf',size = 50,encoding="unic")
draw.text((0.35*width,0.8*height),r"time = %d"%time,fill=120,font = font )
del draw
# saving image
return im
######################################################################
frames = []
counter = 0
for filename in file_names:
frames.append(gen_frame(filename,time=counter, counter=counter))
counter += 1
######################################################################
name = os.path.basename(os.getcwd())
frames[0].save(name+"_timestep"+'.gif', save_all=True, append_images=frames[1::],loop = 5, duration = duration)
拳头图像是我用来制作gif图像的一个例子。第二张图片是我从代码中获得的图片。
-------更新-----
我设法获得了gif并用文本修复了颜色(问题在于设置透明度)。 但是我现在有一个问题,就是gif中的重叠文本。 我绘制的文本在不同的框架中重叠。我现在不知道如何解决此问题。