ImageSequence.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # sequence support classes
  6. #
  7. # history:
  8. # 1997-02-20 fl Created
  9. #
  10. # Copyright (c) 1997 by Secret Labs AB.
  11. # Copyright (c) 1997 by Fredrik Lundh.
  12. #
  13. # See the README file for information on usage and redistribution.
  14. #
  15. ##
  16. class Iterator:
  17. """
  18. This class implements an iterator object that can be used to loop
  19. over an image sequence.
  20. You can use the ``[]`` operator to access elements by index. This operator
  21. will raise an :py:exc:`IndexError` if you try to access a nonexistent
  22. frame.
  23. :param im: An image object.
  24. """
  25. def __init__(self, im):
  26. if not hasattr(im, "seek"):
  27. raise AttributeError("im must have seek method")
  28. self.im = im
  29. self.position = getattr(self.im, "_min_frame", 0)
  30. def __getitem__(self, ix):
  31. try:
  32. self.im.seek(ix)
  33. return self.im
  34. except EOFError as e:
  35. raise IndexError from e # end of sequence
  36. def __iter__(self):
  37. return self
  38. def __next__(self):
  39. try:
  40. self.im.seek(self.position)
  41. self.position += 1
  42. return self.im
  43. except EOFError as e:
  44. raise StopIteration from e
  45. def all_frames(im, func=None):
  46. """
  47. Applies a given function to all frames in an image or a list of images.
  48. The frames are returned as a list of separate images.
  49. :param im: An image, or a list of images.
  50. :param func: The function to apply to all of the image frames.
  51. :returns: A list of images.
  52. """
  53. if not isinstance(im, list):
  54. im = [im]
  55. ims = []
  56. for imSequence in im:
  57. current = imSequence.tell()
  58. ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
  59. imSequence.seek(current)
  60. return [func(im) for im in ims] if func else ims