Search code examples
python-3.xpython-imaging-librarypnggifpython-imageio

Creating a gif from pngs: looping through images seems too fast and only works in debug mode


I'm trying to create a gif image from several (in this case only 5) png files. I can create the gif if I debug the code at the point the looping through the images occurs. Otherwise the execution appears to be too fast. Here is my code:

img, *imgs = [Image.open(f) for f in sorted(glob.glob(png_in))]

So I flattened the list comprehension and added and played around with the time.sleep(x):

ImageFile.LOAD_TRUNCATED_IMAGES = True
imgs = []
for f in sorted(glob.glob(png_in)):
    i = Image.open(f)
    time.sleep(1)
    imgs.append(i)

Then instead of using the PIL module, I switched to the imageio module:

images = []
png_list = sorted(glob.glob(png_in))
for filename in png_list:
    print(f"fn: {filename}")
    images.append(imageio.imread(filename))
    time.sleep(1)
imageio.mimsave(gif_file, images)

Any ideas where I may be going wrong? The error message I get, for example, is:

unknown element "blank"
    i = Image.open(f)

Solution

  • Thanks to Mark Setchell....the problem I found was that the png's were not all there at the point the for loop was executed. I'm using openscad to create png files, and it's here I need to implement a time.sleep. In debug mode, because it's slower, openscad had time to create the png's and so you don't see this problem.