I am trying to make gif using png
images and need to add some information on the data. I have posted the code and the image below. And I dont know what is up and why is it not working. The text does not appear on the image and instead the color of image changes. Which is very weird. I cannot figure out what is wrong with this.
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)
The fist image is an example of one i am using for making the gif. And the second image is the one i get as output from the code.
------- Update -----
I managed to get the gif and fix the color with text (the problem was with the setting the transparency). But I have a problem now with the overlapping text in gif. The text that i draw overlap in different frames. I dont know now how to fix this issue.