siat / postprocess_anchor.py
SlekLi's picture
Upload postprocess_anchor.py
419ba54 verified
Raw
History Blame Contribute Delete
9.27 kB
"""Fuse a fidelity-SR anchor with the high-frequency residual of VARSR outputs."""
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="Blend a fidelity anchor with the high-frequency component of VARSR images.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("--anchor_dir", required=True, help="Directory of SwinIR/HAT fidelity-anchor images.")
parser.add_argument("--varsr_dir", required=True, help="Directory of raw VARSR images at the same HR size.")
parser.add_argument("--output_dir", required=True, help="Directory for anchor + VARSR-frequency targets.")
parser.add_argument(
"--varsr_high_freq_weight",
type=float,
default=0.5,
help="Interpolation from anchor high frequencies (0) to VARSR high frequencies (1).",
)
parser.add_argument("--frequency_levels", type=int, default=5, help="Number of multi-scale frequency levels.")
parser.add_argument(
"--pairing",
choices=("stem", "index"),
default="stem",
help="Pair images by matching relative stems, or explicitly by sorted index when legacy VARSR names differ.",
)
parser.add_argument("--device", choices=("cpu", "cuda"), default="cpu", help="Fusion compute device.")
parser.add_argument("--gpu", type=int, default=0, help="CUDA index used only with --device cuda.")
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.")
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 outputs.")
args = parser.parse_args()
if not 0.0 <= args.varsr_high_freq_weight <= 1.0:
parser.error("--varsr_high_freq_weight must be in [0, 1]")
if args.frequency_levels <= 0:
parser.error("--frequency_levels must be positive")
if 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 resolve_device(args):
if args.device == "cpu":
return torch.device("cpu")
if not torch.cuda.is_available():
raise RuntimeError("--device cuda was requested, but CUDA is unavailable")
if args.gpu >= torch.cuda.device_count():
raise RuntimeError(
f"Requested --gpu {args.gpu}, but PyTorch sees CUDA indices "
f"0..{torch.cuda.device_count() - 1}"
)
return torch.device(f"cuda:{args.gpu}")
def pil_to_tensor(image, device):
array = np.array(image.convert("RGB"), dtype=np.float32, copy=True)
return torch.from_numpy(array).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 multiscale_blur(image, radius):
kernel_values = torch.tensor(
[[0.0625, 0.125, 0.0625], [0.125, 0.25, 0.125], [0.0625, 0.125, 0.0625]],
dtype=image.dtype,
device=image.device,
)
kernel = kernel_values.view(1, 1, 3, 3).repeat(image.shape[1], 1, 1, 1)
padded = functional.pad(image, (radius, radius, radius, radius), mode="replicate")
return functional.conv2d(padded, kernel, groups=image.shape[1], dilation=radius)
def split_high_low_frequency(image, levels):
high_frequency = torch.zeros_like(image)
low_frequency = image
for level in range(levels):
blurred = multiscale_blur(low_frequency, radius=2**level)
high_frequency += low_frequency - blurred
low_frequency = blurred
return high_frequency, low_frequency
def fuse_anchor_and_varsr(anchor, varsr, high_freq_weight, frequency_levels):
anchor_high, _ = split_high_low_frequency(anchor, frequency_levels)
varsr_high, _ = split_high_low_frequency(varsr, frequency_levels)
return (anchor + high_freq_weight * (varsr_high - anchor_high)).clamp(0.0, 1.0)
def output_path_for(reference_path, reference_dir, output_dir, save_ext):
relative_path = reference_path.relative_to(reference_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()
anchor_dir = Path(args.anchor_dir)
varsr_dir = Path(args.varsr_dir)
output_dir = Path(args.output_dir)
extensions = normalize_extensions(args.extensions)
if not anchor_dir.is_dir():
raise FileNotFoundError(f"Anchor directory does not exist: {anchor_dir}")
if not varsr_dir.is_dir():
raise FileNotFoundError(f"VARSR directory does not exist: {varsr_dir}")
anchor_images = index_images(anchor_dir, extensions)
anchor_paths = iter_images(anchor_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}")
if args.pairing == "stem":
image_pairs = []
for varsr_path in varsr_images:
key = relative_stem(varsr_path, varsr_dir)
anchor_path = anchor_images.get(key)
if anchor_path is None:
raise FileNotFoundError(
f"No anchor image matching relative stem '{key}' in {anchor_dir}. "
"If these are corresponding legacy outputs with different names, rerun with --pairing index."
)
image_pairs.append((anchor_path, varsr_path))
else:
if len(anchor_paths) != len(varsr_images):
raise ValueError(
f"--pairing index requires equal image counts, got {len(anchor_paths)} anchor image(s) "
f"and {len(varsr_images)} VARSR image(s)."
)
image_pairs = list(zip(anchor_paths, varsr_images))
device = resolve_device(args)
if device.type == "cuda":
torch.cuda.set_device(device)
print(f"Anchor fusion device: {device} ({torch.cuda.get_device_name(device)})")
else:
print("Anchor fusion device: cpu")
print(
f"Found {len(image_pairs)} image pair(s). Writing to {output_dir}\n"
f"Fusion: target = anchor + beta * (high(VARSR) - high(anchor)); "
f"beta={args.varsr_high_freq_weight}, frequency_levels={args.frequency_levels}, pairing={args.pairing}"
)
for index, (anchor_path, varsr_path) in enumerate(image_pairs, 1):
output_path = output_path_for(anchor_path, anchor_dir, output_dir, args.save_ext)
if output_path.exists() and not args.overwrite:
print(f"[{index}/{len(image_pairs)}] skip existing {output_path}")
continue
with Image.open(anchor_path) as anchor_source, Image.open(varsr_path) as varsr_source:
anchor_image = anchor_source.convert("RGB")
varsr_image = varsr_source.convert("RGB")
if anchor_image.size != varsr_image.size:
raise ValueError(
f"Size mismatch for '{key}': anchor {anchor_image.size}, VARSR {varsr_image.size}"
)
with torch.inference_mode():
anchor_tensor = pil_to_tensor(anchor_image, device)
varsr_tensor = pil_to_tensor(varsr_image, device)
fused_tensor = fuse_anchor_and_varsr(
anchor_tensor,
varsr_tensor,
args.varsr_high_freq_weight,
args.frequency_levels,
)
output_path.parent.mkdir(parents=True, exist_ok=True)
save_kwargs = {"quality": 95} if output_path.suffix.lower() in {".jpg", ".jpeg"} else {}
tensor_to_pil(fused_tensor).save(output_path, **save_kwargs)
print(f"[{index}/{len(image_pairs)}] {varsr_path} + {anchor_path} -> {output_path}")
if __name__ == "__main__":
main()