Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/ImageSequence.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

40 statements  

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## 

17from __future__ import annotations 

18 

19from . import Image 

20 

21TYPE_CHECKING = False 

22if TYPE_CHECKING: 

23 from collections.abc import Callable 

24 from typing import Self 

25 

26 

27class Iterator: 

28 """ 

29 This class implements an iterator object that can be used to loop 

30 over an image sequence. 

31 

32 You can use the ``[]`` operator to access elements by index. This operator 

33 will raise an :py:exc:`IndexError` if you try to access a nonexistent 

34 frame. 

35 

36 :param im: An image object. 

37 """ 

38 

39 def __init__(self, im: Image.Image) -> None: 

40 if not hasattr(im, "seek"): 

41 msg = "im must have seek method" 

42 raise AttributeError(msg) 

43 self.im = im 

44 self.position = getattr(self.im, "_min_frame", 0) 

45 

46 def __getitem__(self, ix: int) -> Image.Image: 

47 try: 

48 self.im.seek(ix) 

49 return self.im 

50 except EOFError as e: 

51 msg = "end of sequence" 

52 raise IndexError(msg) from e 

53 

54 def __iter__(self) -> Self: 

55 return self 

56 

57 def __next__(self) -> Image.Image: 

58 try: 

59 self.im.seek(self.position) 

60 self.position += 1 

61 return self.im 

62 except EOFError as e: 

63 msg = "end of sequence" 

64 raise StopIteration(msg) from e 

65 

66 

67def all_frames( 

68 im: Image.Image | list[Image.Image], 

69 func: Callable[[Image.Image], Image.Image] | None = None, 

70) -> list[Image.Image]: 

71 """ 

72 Applies a given function to all frames in an image or a list of images. 

73 The frames are returned as a list of separate images. 

74 

75 :param im: An image, or a list of images. 

76 :param func: The function to apply to all of the image frames. 

77 :returns: A list of images. 

78 """ 

79 if not isinstance(im, list): 

80 im = [im] 

81 

82 ims = [] 

83 for imSequence in im: 

84 current = imSequence.tell() 

85 

86 ims += [im_frame.copy() for im_frame in Iterator(imSequence)] 

87 

88 imSequence.seek(current) 

89 return [func(im) for im in ims] if func else ims