Python Pillow - 图像序列
Python 图像库 (PIL) 包含对图像序列(动画格式)的一些基本支持。 FLI/FLC、GIF 和一些实验性格式是受支持的序列格式。 TIFF 文件也可以包含多个帧。
打开序列文件,PIL 会自动加载序列中的第一帧。 要在不同帧之间移动,可以使用 seek 和 tell 方法。
from PIL import Image
img = Image.open('bird.jpg')
#Skip to the second frame
img.seek(1)
try:
while 1:
img.seek(img.tell() + 1)
#do_something to img
except EOFError:
#End of sequence
pass
输出
raise EOFError EOFError
正如我们在上面看到的,当序列结束时,你会得到一个 EOFError 异常。
最新版本库中的大多数驱动程序只允许您寻找下一帧(如上例所示),要倒回文件,您可能需要重新打开它。
一个序列迭代器类
class ImageSequence:
def __init__(self, img):
self.img = img
def __getitem__(self, ix):
try:
if ix:
self.img.seek(ix)
return self.img
except EOFError:
raise IndexError # end of sequence
for frame in ImageSequence(img):
# ...do something to frame...

