📜  Python Pillow – 图像序列

📅  最后修改于: 2022-05-13 01:54:29.195000             🧑  作者: Mango

Python Pillow – 图像序列

枕头中的ImageSequence模块包含一个包装类,可帮助用户迭代图像序列的帧。它可以迭代动画、gif 等。

迭代器类

这个类接受一个图像对象作为参数。它实现了一个迭代器对象,用户可以使用它来迭代图像序列。 [ ]运算符可用于按索引访问元素,如果用户尝试访问不存在的索引,则会引发IndexError

句法:

首先,模块ImageImageSequence应该被导入,因为我们将使用Image.open()打开图像或动画文件,在第二个示例中,我们将使用Image.show()显示图像。然后在ImageSequence.Iterator(image_object)方法的帮助下,我们可以迭代帧,还可以提取图像序列中存在的所有帧并将它们保存在文件中。



我们将使用此 Gif 进行演示:

下面是实现:

Python3
# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i = 1
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
    fr.save("frame%d.png"%i)
    i = i + 1


Python3
# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
    app.append(fr)
    fr.save("frame%d.png"%i)
    i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
app[35].show()


Python3
# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
    app.append(fr)
    fr.save("frame%d.png"%i)
    i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
# nonexistent frame it will show
# IndexError
app[36].show()


输出:

动画(gif 文件)共有 36 帧。并且输出将处于 .png 模式。

索引错误示例:



对于这个例子,我们将使用本文之前使用的程序的一些修改版本。我们已经看到,上面的动画总共有 36 帧,索引从 0 到 35。当我们尝试访问第 36 帧时,它会显示IndexError

访问最后一帧:

蟒蛇3

# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
    app.append(fr)
    fr.save("frame%d.png"%i)
    i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
app[35].show()

输出:

访问不存在的框架:

蟒蛇3

# importing the ImageSequence module:
from PIL import Image, ImageSequence
 
# Opening the input gif:
im = Image.open("animation.gif")
 
# create an index variable:
i =1
 
# create an empty list to store the frames:
app = []
 
# iterate over the frames of the gif:
for fr in ImageSequence.Iterator(im):
    app.append(fr)
    fr.save("frame%d.png"%i)
    i = i + 1
 
# print the length of the list of frames.
print(len(app))
 
# nonexistent frame it will show
# IndexError
app[36].show()

输出:

IndexError: list index out of range