File size: 5,662 Bytes
985fb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import argparse
from pathlib import Path

from PIL import Image

from myutils.wavelet_color_fix import wavelet_color_fix


DEFAULT_EXTENSIONS = ".png,.jpg,.jpeg,.JPG,.JPEG"
BICUBIC = Image.Resampling.BICUBIC if hasattr(Image, "Resampling") else Image.BICUBIC


def parse_args():
    parser = argparse.ArgumentParser(
        description="Replace VARSR low frequencies with bicubic-upsampled LR low frequencies.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    parser.add_argument("--lr_dir", required=True, help="Folder containing the original LR images.")
    parser.add_argument("--varsr_dir", required=True, help="Folder containing existing VARSR HR images.")
    parser.add_argument("--output_dir", required=True, help="Folder for wavelet-corrected images.")
    parser.add_argument("--scale", type=int, default=4, help="Expected VARSR enlargement factor.")
    parser.add_argument(
        "--high_freq_weight",
        type=float,
        default=1.0,
        help="Weight of VARSR high frequencies in the corrected image.",
    )
    parser.add_argument("--levels", type=int, default=5, help="Number of wavelet decomposition levels.")
    parser.add_argument("--extensions", default=DEFAULT_EXTENSIONS, help="Comma-separated image extensions.")
    parser.add_argument("--save_ext", default=".png", help="Output extension; empty keeps the VARSR suffix.")
    parser.add_argument("--limit", type=int, default=0, help="Only process the first N images when greater than 0.")
    parser.add_argument("--overwrite", action="store_true", help="Overwrite existing corrected images.")
    args = parser.parse_args()

    if args.scale <= 0:
        parser.error("--scale must be positive")
    if args.high_freq_weight < 0:
        parser.error("--high_freq_weight must be non-negative")
    if args.levels <= 0:
        parser.error("--levels must be positive")
    return args


def normalize_extensions(raw_extensions):
    extensions = set()
    for raw_extension in raw_extensions.split(","):
        extension = raw_extension.strip().lower()
        if extension:
            extensions.add(extension if extension.startswith(".") else f".{extension}")
    return extensions


def iter_images(root, extensions):
    return sorted(
        path
        for path in root.rglob("*")
        if path.is_file() and path.suffix.lower() in extensions
    )


def relative_stem(path, root):
    return path.relative_to(root).with_suffix("").as_posix().lower()


def index_images(root, extensions):
    image_index = {}
    for image_path in iter_images(root, extensions):
        key = relative_stem(image_path, root)
        if key in image_index:
            raise RuntimeError(f"Duplicate relative image stem in {root}: {key}")
        image_index[key] = image_path
    return image_index


def main():
    args = parse_args()
    lr_dir = Path(args.lr_dir)
    varsr_dir = Path(args.varsr_dir)
    output_dir = Path(args.output_dir)
    extensions = normalize_extensions(args.extensions)

    if not lr_dir.is_dir():
        raise FileNotFoundError(f"LR directory does not exist: {lr_dir}")
    if not varsr_dir.is_dir():
        raise FileNotFoundError(f"VARSR directory does not exist: {varsr_dir}")

    lr_images = index_images(lr_dir, extensions)
    varsr_images = iter_images(varsr_dir, extensions)
    if args.limit > 0:
        varsr_images = varsr_images[: args.limit]
    if not varsr_images:
        raise RuntimeError(f"No VARSR images found in {varsr_dir}")

    print(f"Found {len(varsr_images)} VARSR image(s). Writing to {output_dir}")
    print(
        f"Wavelet settings: scale={args.scale}, levels={args.levels}, "
        f"high_freq_weight={args.high_freq_weight}"
    )

    processed = 0
    for index, varsr_path in enumerate(varsr_images, 1):
        key = relative_stem(varsr_path, varsr_dir)
        lr_path = lr_images.get(key)
        if lr_path is None:
            raise FileNotFoundError(f"No LR image matching relative stem '{key}' in {lr_dir}")

        relative_path = varsr_path.relative_to(varsr_dir)
        suffix = args.save_ext if args.save_ext else relative_path.suffix
        if suffix and not suffix.startswith("."):
            suffix = f".{suffix}"
        output_path = (output_dir / relative_path).with_suffix(suffix)
        if output_path.exists() and not args.overwrite:
            print(f"[{index}/{len(varsr_images)}] skip existing {output_path}")
            continue

        with Image.open(lr_path) as lr_source, Image.open(varsr_path) as varsr_source:
            lr_image = lr_source.convert("RGB")
            varsr_image = varsr_source.convert("RGB")

        expected_size = (lr_image.width * args.scale, lr_image.height * args.scale)
        if varsr_image.size != expected_size:
            raise ValueError(
                f"Size mismatch for {varsr_path}: got {varsr_image.size}, expected {expected_size} "
                f"from LR image {lr_path} and scale {args.scale}"
            )

        lr_reference = lr_image.resize(varsr_image.size, BICUBIC)
        corrected = wavelet_color_fix(
            varsr_image,
            lr_reference,
            levels=args.levels,
            high_freq_weight=args.high_freq_weight,
        )
        output_path.parent.mkdir(parents=True, exist_ok=True)
        save_kwargs = {"quality": 95} if output_path.suffix.lower() in {".jpg", ".jpeg"} else {}
        corrected.save(output_path, **save_kwargs)
        processed += 1
        print(f"[{index}/{len(varsr_images)}] {varsr_path} -> {output_path}")

    print(f"Completed: processed={processed}, total={len(varsr_images)}")


if __name__ == "__main__":
    main()