Coverage for src/ensae_teaching_cs/helpers/image_helper.py: 86%
36 statements
« prev ^ index » next coverage.py v7.1.0, created at 2023-04-28 06:23 +0200
« prev ^ index » next coverage.py v7.1.0, created at 2023-04-28 06:23 +0200
1"""
2@file
3@brief image helpers
4"""
5import os
6from PIL import Image
9def collate_images(imgs, final=None):
10 """
11 Collates all images horizontally in one image (if not None --> image name).
13 @param imgs list of image files
14 @param final final image (or None not to save)
15 @return final image (PIL object)
17 It uses the module `Pillow <http://python-imaging.github.io/>`_.
18 """
19 ims = [Image.open(pic) for pic in imgs]
20 size = [_.size for _ in ims]
21 fsize = (sum([_[0] for _ in size]),
22 max([_[1] for _ in size]))
23 blank = Image.new("RGB", fsize, (255, 255, 255))
24 s = 0
25 for im in ims:
26 blank.paste(im, (s, 0))
27 s += im.size[0]
28 if final is not None:
29 blank.save(final)
30 return blank
33def convert_image(imgs, ext, dest=None, fLOG=None):
34 """
35 Converts an image or a list of images into a different format.
37 @param imgs list of images (filenames)
38 @param dest destination folder, if None, the image is saved beside the orginal one
39 @param ext new format
40 @param fLOG logging function
41 @return list of written images
42 """
43 if isinstance(imgs, str):
44 imgs = [imgs]
45 if not isinstance(ext, str):
46 raise TypeError("ext must a string")
47 if len(ext) == 0:
48 raise ValueError("ext must not be empty")
49 if ext.startswith("."):
50 raise ValueError(f"ext must not start with a point '{ext}'")
51 saved = []
52 for img in imgs:
53 if fLOG is not None:
54 fLOG("[convert_image]", img)
55 obj = Image.open(img)
56 if dest is None:
57 folder = os.path.dirname(img)
58 else:
59 folder = dest
60 name = os.path.splitext(os.path.split(img)[-1])[0]
61 new_name = os.path.join(folder, name + "." + ext)
62 obj.save(new_name)
63 saved.append(new_name)
64 return saved