ImageSequence.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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(object):
  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:
  35. raise IndexError # 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:
  44. raise StopIteration
  45. def next(self):
  46. return self.__next__()
  47. def all_frames(im, func=None):
  48. """
  49. Applies a given function to all frames in an image or a list of images.
  50. The frames are returned as a list of separate images.
  51. :param im: An image, or a list of images.
  52. :param func: The function to apply to all of the image frames.
  53. :returns: A list of images.
  54. """
  55. if not isinstance(im, list):
  56. im = [im]
  57. ims = []
  58. for imSequence in im:
  59. current = imSequence.tell()
  60. ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
  61. imSequence.seek(current)
  62. return [func(im) for im in ims] if func else ims