简体   繁体   中英

Custom Frame Duration for Animated Gif in Python ImageIO

I've been playing around with animated gifs in Python, where the frames will be produced by a Raspberry Pi Camera located in a greenhouse. I have used the recommended imageio code from Almar's answer to a previous question with success to create simple gifs.

However, I'm now trying to slow down the frame duration but looking at the documentation for imageio and cannot find any references for mimsave but do see mimwrite , which should take four args. I've looked at the additional gif documentation and can see that there is a duration argument.

Currently, my code looks like:

exportname = "output.gif"
kargs = { 'duration': 5 }
imageio.mimsave(exportname, frames, 'GIF', kargs)

and I'm getting the following error:

Traceback (most recent call last):
File "makegif.py", line 23, in <module>
imageio.mimsave(exportname, frames, 'GIF', kargs)
TypeError: mimwrite() takes at most 3 arguments (4 given)

where frames is a list of imageio.imread objects. Why is this?

UPDATED TO SHOW FULL ANSWER: This is an example showing how to created animated gifs with imageio using kwargs to change the frame duration.

import imageio
import os
import sys

if len(sys.argv) < 2:
  print("Not enough args - add the full path")

indir = sys.argv[1]

frames = []

# Load each file into a list
for root, dirs, filenames in os.walk(indir):
  for filename in filenames:
    if filename.endswith(".jpg"):
        print(filename)
        frames.append(imageio.imread(indir + "/" + filename))


# Save them as frames into a gif 
exportname = "output.gif"
kargs = { 'duration': 5 }
imageio.mimsave(exportname, frames, 'GIF', **kargs)

mimsave does not accept 4 positional arguments. Anything beyond the 3rd argument must be provided as a keyword argument . In other words, you have to unpack kargs like so:

imageio.mimsave(exportname, frames, 'GIF', **kargs)

或者你可以这样称呼它:

imageio.mimsave(exportname, frames, format='GIF', duration=5)

I've found this to be the simplest and most robust solution

import imageio
import os

path = '/path/to/script/and/frames'
image_folder = os.fsencode(path)

filenames = []

for file in os.listdir(image_folder):
    filename = os.fsdecode(file)
    if filename.endswith( ('.jpeg', '.png', '.gif') ):
        filenames.append(filename)

filenames.sort() # this iteration technique has no built in order, so sort the frames

images = list(map(lambda filename: imageio.imread(filename), filenames))

and then this last line of the script is the one you are looking for

imageio.mimsave(os.path.join('my_very_own_gif.gif'), images, duration = 0.04) # modify the frame duration as needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM