import os import argparse from PIL import Image from tqdm import tqdm from pathlib import Path def run(src: Path, target: Path, root: Path, scale_factor: float = 1., width: int = -1, height: int = -1): target.mkdir(exist_ok=True) for file_name in tqdm(os.listdir(src), leave=False, desc=src.relative_to(root).__str__()): if (src / file_name).is_dir(): run(src / file_name, target / file_name, root, scale_factor, width, height) elif not (target / file_name).exists(): postfix = os.path.splitext(file_name)[1] if postfix == '.jpg' or postfix == '.png': im = Image.open(src / file_name) if width == -1 and height == -1: width = round(im.width * scale_factor) height = round(im.height * scale_factor) elif width == -1: width = round(im.width / im.height * height) elif height == -1: height = round(im.height / im.width * width) im = im.resize((width, height)) im.save(target / file_name) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('src', type=str, help='Source directory.') parser.add_argument('target', type=str, help='Target directory.') parser.add_argument('-x', '--scale-factor', type=float, default=1, help='Target directory.') parser.add_argument('--width', type=int, default=-1, help='Width of output images (pixel)') parser.add_argument('--height', type=int, default=-1, help='Height of output images (pixel)') opt = parser.parse_args() run(Path(opt.src), Path(opt.target), Path(opt.src), opt.scale_factor, opt.width, opt.height)