-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
66 lines (48 loc) · 1.89 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import argparse
import os
import glob
from typing import Tuple
from PIL import Image, ImageOps
from PIL.Image import Image as ImageType
THUMBNAIL_SIZE = (2000, 2000)
BORDER_PADDING = 60
BORDER_COLOR = 'white'
def resize_square(image: ImageType, fill_color: Tuple[int] = (255, 255, 255)):
width, height = image.size
side_length = max(width, height)
resized_image = Image.new('RGB', (side_length, side_length), fill_color)
resized_image.paste(
image, (int((side_length - width) / 2),
int((side_length - height) / 2)))
resized_image.thumbnail(THUMBNAIL_SIZE, Image.Resampling.LANCZOS)
return resized_image
def parse_arguments():
parser = argparse.ArgumentParser(description='A simple utility for adding borders to images')
parser.add_argument('--src',
type=directory_path,
help='image source directory (only JPG files are transformed)',
required=True)
parser.add_argument('--dst',
type=directory_path,
help='image output directory',
required=True)
return parser.parse_args()
def directory_path(path: str):
if os.path.isdir(path):
return path
else:
raise argparse.ArgumentTypeError(
f"Given path {path} is not a valid directory")
def main():
parsed_arguments = parse_arguments()
source_paths = glob.glob(os.path.join(parsed_arguments.src, '*.jpg'))
for source_path in source_paths:
_, filename = os.path.split(source_path)
image = Image.open(source_path)
square_image = resize_square(image)
padded_square_image = ImageOps.expand(
square_image, BORDER_PADDING, BORDER_COLOR)
padded_square_image.save(os.path.join(
parsed_arguments.dst, filename), quality=100)
if __name__ == '__main__':
main()