Now using argparse.
[toast/gimp_passport.git] / gimp_passport.py
1 import argparse
2 from PIL import Image
3
4 def make_passport(image_filename: str, fpr: float, width_mm: float, height_mm: float) -> Image:
5     """
6     :param fpr: face to picture ratio, e.g. 2/3
7     """
8     img_rgba = Image.open(image_filename)
9
10     # get bounding box of head
11     bands = img_rgba.getbands()
12     if 'A' not in bands:
13         raise ValueError('Image has no transparency (needed for marking the head).')
14     alpha = img_rgba.getdata(bands.index('A'))
15     bbox_head = alpha.getbbox()  # bounding box of head
16
17
18     # get bounding box of passport image ("pic")
19     left, top, right, bottom = bbox_head
20     height = bottom - top
21     width = right - left
22     pic_height = int(round(height / fpr))
23     pic_width = int(round(pic_height * width_mm / height_mm))
24     pic_top = top - (pic_height - height) // 2
25     pic_bottom = pic_top + pic_height
26     pic_left = left - (pic_width - width) // 2
27     pic_right = pic_left + pic_width
28     bbox_pic = pic_left, pic_top, pic_right, pic_bottom
29
30     # cut image
31     img = img_rgba.convert('RGB')  # drop alpha channel
32     pic = img.crop(bbox_pic)
33     return pic
34
35
36 def main(source_image: str, dest_image: str):
37     pic = make_passport(source_image, 0.75, 35., 45.)
38     pic.save(dest_image)
39
40
41 if __name__ == '__main__':
42     description = 'Convert image with alpha mask marking the face to passport image.'
43     parser = argparse.ArgumentParser(description=description)
44     parser.add_argument('source', help='sourse image')
45     parser.add_argument('dest', help='destination image')
46     args = parser.parse_args()
47     main(args.source, args.dest)
48