ImageSequence.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. from __future__ import annotations
  17. TYPE_CHECKING = False
  18. if TYPE_CHECKING:
  19. from collections.abc import Callable
  20. from typing import Self
  21. from . import Image
  22. class Iterator:
  23. """
  24. This class implements an iterator object that can be used to loop
  25. over an image sequence.
  26. You can use the ``[]`` operator to access elements by index. This operator
  27. will raise an :py:exc:`IndexError` if you try to access a nonexistent
  28. frame.
  29. :param im: An image object.
  30. """
  31. def __init__(self, im: Image.Image) -> None:
  32. if not hasattr(im, "seek"):
  33. msg = "im must have seek method"
  34. raise AttributeError(msg)
  35. self.im = im
  36. self.position = getattr(self.im, "_min_frame", 0)
  37. def __getitem__(self, ix: int) -> Image.Image:
  38. try:
  39. self.im.seek(ix)
  40. return self.im
  41. except EOFError as e:
  42. msg = "end of sequence"
  43. raise IndexError(msg) from e
  44. def __iter__(self) -> Self:
  45. return self
  46. def __next__(self) -> Image.Image:
  47. try:
  48. self.im.seek(self.position)
  49. self.position += 1
  50. return self.im
  51. except EOFError as e:
  52. msg = "end of sequence"
  53. raise StopIteration(msg) from e
  54. def all_frames(
  55. im: Image.Image | list[Image.Image],
  56. func: Callable[[Image.Image], Image.Image] | None = None,
  57. ) -> list[Image.Image]:
  58. """
  59. Applies a given function to all frames in an image or a list of images.
  60. The frames are returned as a list of separate images.
  61. :param im: An image, or a list of images.
  62. :param func: The function to apply to all of the image frames.
  63. :returns: A list of images.
  64. """
  65. if not isinstance(im, list):
  66. im = [im]
  67. ims = []
  68. for imSequence in im:
  69. current = imSequence.tell()
  70. try:
  71. ims += [im_frame.copy() for im_frame in Iterator(imSequence)]
  72. finally:
  73. imSequence.seek(current)
  74. return [func(im) for im in ims] if func else ims