Tho*_* B. 3 python gif animated-gif python-imaging-library python-3.x
在 python 中,我用 PIL 加载了一个 gif。我提取第一帧,修改它,然后放回去。我用以下代码保存修改后的gif
imgs[0].save('C:\\etc\\test.gif',
save_all=True,
append_images=imgs[1:],
duration=10,
loop=0)
Run Code Online (Sandbox Code Playgroud)
其中 imgs 是组成 gif 的图像数组,持续时间是帧之间的延迟(以毫秒为单位)。我想让持续时间值与原始 gif 相同,但我不确定如何提取 gif 的总持续时间或每秒显示的帧数。
据我所知,gifs 的头文件不提供任何 fps 信息。
有谁知道我如何获得正确的持续时间值?
提前致谢
编辑:要求的 gif 示例:

从这里取回。
在 GIF 文件中,每一帧都有自己的持续时间。所以GIF文件没有通用的fps。PIL 支持这一点的方式是提供一个info给出duration当前帧的dict 。您可以使用seek和tell遍历帧并计算总持续时间。
这是一个计算 GIF 文件每秒平均帧数的示例程序。
import os
from PIL import Image
FILENAME = os.path.join(os.path.dirname(__file__),
'Rotating_earth_(large).gif')
def get_avg_fps(PIL_Image_object):
""" Returns the average framerate of a PIL Image object """
PIL_Image_object.seek(0)
frames = duration = 0
while True:
try:
frames += 1
duration += PIL_Image_object.info['duration']
PIL_Image_object.seek(PIL_Image_object.tell() + 1)
except EOFError:
return frames / duration * 1000
return None
def main():
img_obj = Image.open(FILENAME)
print(f"Average fps: {get_avg_fps(img_obj)}")
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
如果您假设duration所有帧都相等,则可以执行以下操作:
print(1000 / Image.open(FILENAME).info['duration'])
Run Code Online (Sandbox Code Playgroud)