Python,我怎么能得到GIF帧

Kul*_*ula 4 python frame

我正在寻找一种获得gif帧数的方法.我正在寻找谷歌,stackoverflow和任何外部网站,我只发现垃圾!有人知道怎么做吗?我只需要简单数量的gif帧.

adw*_*adw 15

只需解析文件,gif非常简单:

class GIFError(Exception): pass

def get_gif_num_frames(filename):
    frames = 0
    with open(filename, 'rb') as f:
        if f.read(6) not in ('GIF87a', 'GIF89a'):
            raise GIFError('not a valid GIF file')
        f.seek(4, 1)
        def skip_color_table(flags):
            if flags & 0x80: f.seek(3 << ((flags & 7) + 1), 1)
        flags = ord(f.read(1))
        f.seek(2, 1)
        skip_color_table(flags)
        while True:
            block = f.read(1)
            if block == ';': break
            if block == '!': f.seek(1, 1)
            elif block == ',':
                frames += 1
                f.seek(8, 1)
                skip_color_table(ord(f.read(1)))
                f.seek(1, 1)
            else: raise GIFError('unknown block type')
            while True:
                l = ord(f.read(1))
                if not l: break
                f.seek(l, 1)
    return frames
Run Code Online (Sandbox Code Playgroud)


Der*_*ger 12

您使用哪种方法来加载/操作框架?你在用PIL吗?如果没有,我建议检查一下:Python Imaging Library,特别是PIL gif页面.

现在,假设您使用PIL读取gif,确定您正在查看哪个帧是一件非常简单的事情.搜索将转到特定的框架并告诉将返回您正在查看的框架.

from PIL import Image
im = Image.open("animation.gif")

# To iterate through the entire gif
try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence
Run Code Online (Sandbox Code Playgroud)

否则,我相信你只能通过搜索找到gif中的帧数,直到引发异常(EOFError).

  • 我必须将“导入图像”更改为“从 PIL 导入图像”才能使其工作(我猜我安装了最新的 Pillow 版本) (2认同)

asm*_*asm 6

我最近遇到了同样的问题,发现 GIF 的文档特别缺乏。这是我的解决方案,使用imageio 的 get_reader读取图像的字节(例如,如果您只是通过 HTTP 获取图像,则很有用),它可以方便地将帧存储在numpy 矩阵中:

import imageio
gif = imageio.get_reader(image_bytes, '.gif')

# Here's the number you're looking for
number_of_frames = len(gif)

for frame in gif:
  # each frame is a numpy matrix
Run Code Online (Sandbox Code Playgroud)

如果您只需要打开一个文件,请使用:

gif = imageio.get_reader('cat.gif')
Run Code Online (Sandbox Code Playgroud)