| import os |
| import cv2 |
| import torch |
| import argparse |
| import numpy as np |
| import torch.nn as nn |
| import torch.nn.functional as F |
| from skimage import img_as_ubyte |
| |
| from xrestormer.archs.xrestormer_arch import XRestormer |
| import yaml |
|
|
| def load_img(filepath): |
| with open(filepath, 'rb') as f: |
| value_buf = f.read() |
| img_np = np.frombuffer(value_buf, np.uint8) |
| img = cv2.imdecode(img_np, cv2.IMREAD_COLOR) |
| |
| img = img.astype(np.float32) / 255. |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) |
| |
|
|
| def save_img(filepath, img): |
| cv2.imwrite(filepath, cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) |
|
|
| def load_model(yaml_path, weight_path): |
| """加载 Restormer 模型""" |
| try: |
| from yaml import CLoader as Loader |
| except ImportError: |
| from yaml import Loader |
|
|
| with open(yaml_path, mode='r') as f: |
| config = yaml.load(f, Loader=Loader) |
|
|
| net_config = config['network_g'] |
| net_type = net_config.pop('type', None) |
| model = XRestormer(**net_config) |
| |
| |
| model.cuda() |
| model.eval() |
| return model |
|
|
| def restore_image(model, input_image_path, output_image_path, factor=64): |
| """用模型复原单张图片""" |
| img_t = load_img(input_image_path) |
| |
| |
|
|
| |
| h, w = img_t.shape[2], img_t.shape[3] |
| H, W = ((h + factor) // factor) * factor, ((w + factor) // factor) * factor |
| padh, padw = H - h, W - w |
| if padh != 0 or padw != 0: |
| img_t = F.pad(img_t, (0, padw, 0, padh), 'reflect') |
|
|
| with torch.no_grad(): |
| restored = model(img_t) |
| restored = restored[:, :, :h, :w] |
| restored = torch.clamp(restored, 0, 1).cpu().permute(0, 2, 3, 1).squeeze(0).numpy() |
|
|
| save_img(output_image_path, img_as_ubyte(restored)) |
| print(f"✅ Saved restored image to: {output_image_path}") |
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Single image restoration using Restormer") |
| parser.add_argument("--input", required=True, type=str, help="Path to input image") |
| parser.add_argument("--output", required=True, type=str, help="Path to save output image") |
| parser.add_argument("--model", required=True, choices=['xrestormer.gaussian_denoise'], |
| help="Model type to use") |
| args = parser.parse_args() |
|
|
| |
| model_configs = { |
| "xrestormer.gaussian_denoise": { |
| "yaml": "/hdd/Restoration/X-Restormer/options/test/002_xrestormer_denoise.yml", |
| "weights": "/hdd/Restoration/Inference/Restormer/Denoising/pretrained_models/gaussian_color_denoising_sigma15.pth" |
| }, |
|
|
| } |
|
|
| config = model_configs[args.model] |
| model = load_model(config["yaml"], config["weights"]) |
| restore_image(model, args.input, args.output) |
|
|