| """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): |
| |
| 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() |
|
|