Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Helpers around images. 

4 

5.. versionadded:: 1.9 

6""" 

7import os 

8import glob 

9import numpy 

10 

11 

12def zoom_img(img, factor=1., max_dim=None, out_file=None, fLOG=None): 

13 """ 

14 Zooms an image. 

15 

16 :param img: image or filename or pattern 

17 :param factor: multiplies the image by this factor if not None 

18 :param max_dim: modifies the image, the highest dimension 

19 should below this number 

20 :param out_file: stores the image into this file if not None 

21 :param fLOG: logging function 

22 :return: image 

23 """ 

24 if isinstance(img, str): 

25 if '*' in img: 

26 found = glob.glob(img) 

27 res = [] 

28 for im in found: 

29 if out_file is None: 

30 i = zoom_img(im, factor=factor, max_dim=max_dim, fLOG=fLOG) 

31 else: 

32 of = out_file.format(os.path.split(im)[-1]) 

33 i = zoom_img(im, factor=factor, max_dim=max_dim, 

34 out_file=of, fLOG=fLOG) 

35 res.append(i) 

36 if len(res) == 0: 

37 raise FileNotFoundError( # pragma: no cover 

38 "Unable to find anything in '{}'.".format(img)) 

39 return res 

40 from PIL import Image 

41 obj = Image.open(img) 

42 elif hasattr(img, 'size'): 

43 obj = img 

44 else: 

45 raise TypeError( # pragma: no cover 

46 "Image should be a string or an image not {}.".format(type(img))) 

47 dx, dy = obj.size 

48 if max_dim is not None: 

49 if not isinstance(max_dim, int): 

50 max_dim = int(max_dim) 

51 facx = max_dim * 1. / max(dx, 1) 

52 facy = max_dim * 1. / max(dy, 1) 

53 factor = min(facx, facy) 

54 if factor is not None: 

55 if not isinstance(factor, float): 

56 factor = int(factor) 

57 dx = int(dx * factor + 0.5) 

58 dy = int(dy * factor + 0.5) 

59 obj = obj.resize((dx, dy)) 

60 if out_file is not None: 

61 if fLOG is not None: 

62 fLOG("Writing '{}' dim=({},{}).".format(out_file, dx, dy)) 

63 obj.save(out_file) 

64 return obj 

65 

66 

67def white_to_transparency(img, out_file=None): 

68 """ 

69 Sets white color as transparency color. 

70 

71 @param img image (:epkg:`Pillow`) 

72 @param out_file stores the image into this file if not None 

73 @return image (:epkg:`Pillow`) 

74 

75 Code taken from `Using PIL to make all white pixels transparent? 

76 <https://stackoverflow.com/questions/765736/ 

77 using-pil-to-make-all-white-pixels-transparent>`_. 

78 

79 .. versionadded:: 1.9 

80 """ 

81 from PIL import Image 

82 if isinstance(img, str): 

83 img = Image.open(img) 

84 x = numpy.asarray(img.convert('RGBA')).copy() 

85 

86 x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(numpy.uint8) 

87 

88 obj = Image.fromarray(x) 

89 if out_file is not None: 

90 obj.save(out_file) 

91 return obj