"""Script to convert image sizes.""" import os import argparse from PIL import Image from concurrent.futures import ThreadPoolExecutor from tqdm import tqdm def parse_args(): parser = argparse.ArgumentParser( description="Batch resize images preserving directory structure" ) parser.add_argument( "--input_dir", type=str, help="Path to the input directory containing images" ) parser.add_argument( "--output_dir", type=str, help="Path to the directory where resized images will be saved" ) parser.add_argument( "--ext", type=str, default="png", help="Target image extension to process (e.g., png, jpg)" ) parser.add_argument( "--size", type=int, nargs=2, required=True, metavar=("WIDTH", "HEIGHT"), help="Target size for resizing (width height)" ) parser.add_argument( "--mode", type=str, choices=["nearest", "bilinear", "bicubic", "lanczos"], default="lanczos", help="Resampling filter mode to use when resizing" ) parser.add_argument( "--workers", type=int, default=os.cpu_count(), help=f"Number of parallel workers. Set to -1 to use all cpu cores: {os.cpu_count()}" ) return parser.parse_args() def process_file(src_path, dst_path, size, resample): try: os.makedirs(os.path.dirname(dst_path), exist_ok=True) with Image.open(src_path) as img: img = img.convert("RGB") img = img.resize(size, resample) img.save(dst_path) return True, src_path except Exception as e: return False, f"{src_path}: {e}" def main(): args = parse_args() ext = args.ext.lower().lstrip('.') size = tuple(args.size) num_workers = os.cpu_count() if args.workers == -1 else args.workers # Map mode to Pillow resampling filter resample_map = { "nearest": Image.NEAREST, "bilinear": Image.BILINEAR, "bicubic": Image.BICUBIC, "lanczos": Image.LANCZOS, } resample = resample_map[args.mode] # Collect all matching files tasks = [] for root, _, files in os.walk(args.input_dir): for fname in files: if fname.lower().endswith(f".{ext}"): src_path = os.path.join(root, fname) rel_path = os.path.relpath(src_path, args.input_dir) dst_path = os.path.join(args.output_dir, rel_path) dst_path = os.path.splitext(dst_path)[0] + f".{ext}" tasks.append((src_path, dst_path)) total = len(tasks) if total == 0: print(f"No files with extension .{ext} found in {args.input_dir}") return print(f"Resizing {total} files to {size[0]}x{size[1]} using {num_workers} workers with {args.mode} filter...") failures = [] with ThreadPoolExecutor(max_workers=num_workers) as executor: futures = [executor.submit(process_file, src, dst, size, resample) for src, dst in tasks] for future in tqdm(futures, total=total): success, info = future.result() if not success: failures.append(info) print(f"\nCompleted. {total - len(failures)} succeeded, {len(failures)} failed.") if failures: print("Failures:") for err in failures: print(" ", err) if __name__ == "__main__": main() print("DONE.")