【问题标题】:Custom Frame Duration for Animated Gif in Python ImageIOPython ImageIO 中动画 Gif 的自定义帧持续时间
【发布时间】:2016-07-18 09:42:42
【问题描述】:

我一直在玩 Python 中的动画 gif,其中帧将由位于温室中的 Raspberry Pi 相机生成。我已经成功地使用了来自Almar's answer to a previous question 的推荐 imageio 代码来创建简单的 gif。

但是,我现在正试图减慢帧持续时间,但查看 documentation for imageio 并找不到任何有关 mimsave 的引用,但确实看到了 mimwrite,这应该需要四个参数。我查看了additional gif documentation,可以看到有一个持续时间参数。

目前,我的代码如下:

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

我收到以下错误:

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)

其中 frames 是 imageio.imread 对象的列表。这是为什么呢?

已更新以显示完整答案: 这是一个示例,展示了如何使用 imageio 创建动画 gif,使用 kwargs 来更改帧持续时间。

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)

【问题讨论】:

    标签: python image animation


    【解决方案1】:

    或者你可以这样称呼它:

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

    【讨论】:

    • 在 imageio 版本 '2.5.0' 中,我们必须将 FPS 直接作为 'fps' 参数而不是持续时间。 imageio.imsave(exportname, frames, format='GIF', fps=30)
    【解决方案2】:

    mimsave 不接受 4 个位置 参数。第三个参数以外的任何内容都必须作为关键字参数提供。换句话说,你必须像这样解压kargs:

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

    【讨论】:

      【解决方案3】:

      我发现这是最简单、最可靠的解决方案

      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))
      

      然后脚本的最后一行就是您要查找的那一行

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-21
        • 2021-03-27
        • 2017-01-27
        • 2012-11-17
        • 1970-01-01
        • 2018-06-15
        • 2021-02-04
        • 2014-03-27
        相关资源
        最近更新 更多