2010-07-31 06:52:47 +04:00
|
|
|
#
|
|
|
|
# The Python Imaging Library.
|
|
|
|
# $Id$
|
|
|
|
#
|
|
|
|
# sequence support classes
|
|
|
|
#
|
|
|
|
# history:
|
|
|
|
# 1997-02-20 fl Created
|
|
|
|
#
|
|
|
|
# Copyright (c) 1997 by Secret Labs AB.
|
|
|
|
# Copyright (c) 1997 by Fredrik Lundh.
|
|
|
|
#
|
|
|
|
# See the README file for information on usage and redistribution.
|
|
|
|
#
|
|
|
|
|
|
|
|
##
|
|
|
|
|
2014-08-26 17:47:10 +04:00
|
|
|
|
2019-09-30 17:56:31 +03:00
|
|
|
class Iterator:
|
2013-10-14 08:49:35 +04:00
|
|
|
"""
|
|
|
|
This class implements an iterator object that can be used to loop
|
|
|
|
over an image sequence.
|
2010-07-31 06:52:47 +04:00
|
|
|
|
2013-10-14 08:49:35 +04:00
|
|
|
You can use the ``[]`` operator to access elements by index. This operator
|
|
|
|
will raise an :py:exc:`IndexError` if you try to access a nonexistent
|
|
|
|
frame.
|
|
|
|
|
|
|
|
:param im: An image object.
|
|
|
|
"""
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def __init__(self, im):
|
|
|
|
if not hasattr(im, "seek"):
|
|
|
|
raise AttributeError("im must have seek method")
|
|
|
|
self.im = im
|
2019-06-12 13:11:51 +03:00
|
|
|
self.position = getattr(self.im, "_min_frame", 0)
|
2010-07-31 06:52:47 +04:00
|
|
|
|
|
|
|
def __getitem__(self, ix):
|
|
|
|
try:
|
2016-01-27 06:04:05 +03:00
|
|
|
self.im.seek(ix)
|
2010-07-31 06:52:47 +04:00
|
|
|
return self.im
|
2020-06-21 13:13:35 +03:00
|
|
|
except EOFError as e:
|
|
|
|
raise IndexError from e # end of sequence
|
2016-01-06 13:09:40 +03:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __next__(self):
|
|
|
|
try:
|
|
|
|
self.im.seek(self.position)
|
|
|
|
self.position += 1
|
|
|
|
return self.im
|
2020-06-21 13:13:35 +03:00
|
|
|
except EOFError as e:
|
|
|
|
raise StopIteration from e
|
2016-01-06 13:09:40 +03:00
|
|
|
|
2019-06-23 00:34:39 +03:00
|
|
|
|
|
|
|
def all_frames(im, func=None):
|
|
|
|
"""
|
|
|
|
Applies a given function to all frames in an image or a list of images.
|
|
|
|
The frames are returned as a list of separate images.
|
|
|
|
|
|
|
|
:param im: An image, or a list of images.
|
|
|
|
:param func: The function to apply to all of the image frames.
|
|
|
|
:returns: A list of images.
|
|
|
|
"""
|
|
|
|
if not isinstance(im, list):
|
|
|
|
im = [im]
|
|
|
|
|
|
|
|
ims = []
|
|
|
|
for imSequence in im:
|
|
|
|
current = imSequence.tell()
|
|
|
|
|
|
|
|
ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
|
|
|
|
|
|
|
|
imSequence.seek(current)
|
|
|
|
return [func(im) for im in ims] if func else ims
|