From f25cece253377e57554d29c24d42fabe4feb3cf5 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Mon, 8 Apr 2019 13:04:16 +1000 Subject: [PATCH] Added ImageSequence all_frames --- Tests/test_imagesequence.py | 22 ++++++++++++++++++++++ src/PIL/ImageSequence.py | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/Tests/test_imagesequence.py b/Tests/test_imagesequence.py index 9fbf3fed8a7..53ac8375adf 100644 --- a/Tests/test_imagesequence.py +++ b/Tests/test_imagesequence.py @@ -69,3 +69,25 @@ def test_palette_mmap(self): im.seek(0) color2 = im.getpalette()[0:3] self.assertEqual(color1, color2) + + def test_all_frames(self): + # Test a single image + im = Image.open('Tests/images/g4-multi.tiff') + ims = ImageSequence.all_frames(im) + + self.assertEqual(len(ims), 3) + for i, im_frame in enumerate(ims): + self.assertFalse(im_frame is im) + + im.seek(i) + self.assert_image_equal(im, im_frame) + + # Test a series of images + ims = ImageSequence.all_frames([im, hopper(), im]) + self.assertEqual(len(ims), 7) + + # Test an operation + ims = ImageSequence.all_frames(im, lambda im_frame: im_frame.rotate(180)) + for i, im_frame in enumerate(ims): + im.seek(i) + self.assert_image_equal(im.rotate(180), im_frame) diff --git a/src/PIL/ImageSequence.py b/src/PIL/ImageSequence.py index 1fc6e5de165..24115ddf034 100644 --- a/src/PIL/ImageSequence.py +++ b/src/PIL/ImageSequence.py @@ -54,3 +54,25 @@ def __next__(self): def next(self): return self.__next__() + + +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