File size: 3,413 Bytes
31d2139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""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.")