File size: 10,797 Bytes
2ae6858
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""Apply iterative LR back-projection to precomputed VARSR outputs.

This is intentionally independent of infer_folder.py and of all Wavelet/AdaIN
post-processing.  It consumes an original LR image y and a precomputed VARSR
image x, then applies the classical iterative back-projection update:

    x_{t+1} = clip(x_t + eta * U(y - D(x_t)), 0, 1)

D is bicubic downsampling with antialiasing, matching the LR fidelity loss in
3DSR's train_3dsr.py.  U is bicubic upsampling to the VARSR image resolution.
"""

import argparse
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as functional
from PIL import Image


DEFAULT_EXTENSIONS = ".png,.jpg,.jpeg,.JPG,.JPEG"


def parse_args():
    parser = argparse.ArgumentParser(
        description="Apply LR data-consistency back-projection to existing VARSR outputs.",
        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 raw VARSR HR outputs.")
    parser.add_argument("--output_dir", required=True, help="Folder for LR-back-projected HR images.")
    parser.add_argument("--scale", type=int, default=4, help="Expected VARSR enlargement factor.")
    parser.add_argument("--iterations", type=int, default=1, help="Number of iterative back-projection updates.")
    parser.add_argument("--step_size", type=float, default=1.0, help="Back-projection step size eta.")
    parser.add_argument(
        "--device",
        choices=("auto", "cpu", "cuda"),
        default="cpu",
        help="Compute device. CPU is the default because this postprocess is small and avoids inference GPU contention.",
    )
    parser.add_argument(
        "--gpu",
        type=int,
        default=None,
        help="Physical CUDA index used only with --device cuda/auto. Do not combine with CUDA_VISIBLE_DEVICES.",
    )
    parser.add_argument("--extensions", default=DEFAULT_EXTENSIONS, help="Comma-separated image extensions.")
    parser.add_argument("--save_ext", default=".png", help="Output extension. PNG is recommended to avoid lossy re-encoding.")
    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.iterations <= 0:
        parser.error("--iterations must be positive")
    if args.step_size <= 0:
        parser.error("--step_size must be positive")
    if args.gpu is not None and args.gpu < 0:
        parser.error("--gpu must be non-negative")
    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 basename_stem(path):
    return path.stem.lower()


def index_unique_basenames(root, extensions):
    """Index images by filename stem, rejecting ambiguous flat-name matches."""
    image_index = {}
    for image_path in iter_images(root, extensions):
        key = basename_stem(image_path)
        if key in image_index:
            raise RuntimeError(
                f"Duplicate image basename '{key}' in {root}: "
                f"{image_index[key]} and {image_path}. "
                "Use directories with matching relative paths instead."
            )
        image_index[key] = image_path
    return image_index


def find_lr_image(lr_images_by_relative_path, lr_images_by_basename, varsr_path, varsr_dir, lr_dir):
    """Match relative paths first, then support 3DSR-rendered nested VARSR outputs."""
    relative_key = relative_stem(varsr_path, varsr_dir)
    lr_path = lr_images_by_relative_path.get(relative_key)
    if lr_path is not None:
        return lr_path

    basename_key = basename_stem(varsr_path)
    lr_path = lr_images_by_basename.get(basename_key)
    if lr_path is not None:
        return lr_path

    raise FileNotFoundError(
        f"No LR image matching VARSR image '{varsr_path}'. Tried relative stem "
        f"'{relative_key}' and basename '{basename_key}' in {lr_dir}."
    )


def resolve_device(args):
    if args.device == "cpu":
        return torch.device("cpu")
    if not torch.cuda.is_available():
        if args.device == "cuda":
            raise RuntimeError("--device cuda was requested, but CUDA is unavailable")
        return torch.device("cpu")

    gpu = 0 if args.gpu is None else args.gpu
    if gpu >= torch.cuda.device_count():
        raise RuntimeError(
            f"Requested --gpu {gpu}, but PyTorch sees CUDA indices 0..{torch.cuda.device_count() - 1}. "
            "If CUDA_VISIBLE_DEVICES is set, remove it when selecting a physical GPU with --gpu."
        )
    return torch.device(f"cuda:{gpu}")


def pil_to_tensor(image, device):
    # np.array creates writable storage because the tensor is normalized in place below.
    tensor = torch.from_numpy(np.array(image, dtype=np.float32, copy=True))
    return tensor.permute(2, 0, 1).unsqueeze(0).div_(255.0).to(device)


def tensor_to_pil(tensor):
    array = (
        tensor.detach()
        .squeeze(0)
        .permute(1, 2, 0)
        .clamp(0.0, 1.0)
        .mul(255.0)
        .round()
        .to(torch.uint8)
        .cpu()
        .numpy()
    )
    return Image.fromarray(array, mode="RGB")


def downsample_to_lr(hr, lr_size):
    return functional.interpolate(hr, size=lr_size, mode="bicubic", antialias=True)


def lr_backproject(hr, lr, iterations, step_size):
    """Perform K classical bicubic iterative-back-projection updates."""
    corrected = hr
    for _ in range(iterations):
        residual = lr - downsample_to_lr(corrected, lr.shape[-2:])
        correction = functional.interpolate(
            residual, size=corrected.shape[-2:], mode="bicubic", antialias=True
        )
        corrected = (corrected + step_size * correction).clamp(0.0, 1.0)
    return corrected


def lr_mae(hr, lr):
    return (downsample_to_lr(hr, lr.shape[-2:]) - lr).abs().mean().item()


def output_path_for(varsr_path, varsr_dir, output_dir, save_ext):
    relative_path = varsr_path.relative_to(varsr_dir)
    suffix = save_ext if save_ext else relative_path.suffix
    if suffix and not suffix.startswith("."):
        suffix = f".{suffix}"
    return (output_dir / relative_path).with_suffix(suffix)


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)
    lr_images_by_basename = index_unique_basenames(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}")

    device = resolve_device(args)
    if device.type == "cuda":
        torch.cuda.set_device(device)
        print(f"LR back-projection device: {device} ({torch.cuda.get_device_name(device)})")
    else:
        print("LR back-projection device: cpu")
    print(
        f"Found {len(varsr_images)} VARSR image(s). Writing to {output_dir}\n"
        f"LRBP settings: scale={args.scale}, iterations={args.iterations}, step_size={args.step_size}"
    )

    processed = 0
    pre_mae_total = 0.0
    post_mae_total = 0.0
    for index, varsr_path in enumerate(varsr_images, 1):
        lr_path = find_lr_image(
            lr_images,
            lr_images_by_basename,
            varsr_path,
            varsr_dir,
            lr_dir,
        )

        output_path = output_path_for(varsr_path, varsr_dir, output_dir, args.save_ext)
        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}"
            )

        with torch.inference_mode():
            lr_tensor = pil_to_tensor(lr_image, device)
            hr_tensor = pil_to_tensor(varsr_image, device)
            pre_mae = lr_mae(hr_tensor, lr_tensor)
            corrected_tensor = lr_backproject(
                hr_tensor, lr_tensor, iterations=args.iterations, step_size=args.step_size
            )
            post_mae = lr_mae(corrected_tensor, lr_tensor)
            corrected = tensor_to_pil(corrected_tensor)

        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
        pre_mae_total += pre_mae
        post_mae_total += post_mae
        print(
            f"[{index}/{len(varsr_images)}] {varsr_path} -> {output_path} "
            f"LR-MAE: {pre_mae:.6f} -> {post_mae:.6f}"
        )

    if processed:
        print(
            f"Completed: processed={processed}, total={len(varsr_images)}, "
            f"mean LR-MAE={pre_mae_total / processed:.6f} -> {post_mae_total / processed:.6f}"
        )
    else:
        print(f"Completed: processed=0, total={len(varsr_images)}")


if __name__ == "__main__":
    main()