File size: 3,092 Bytes
06f2b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 basicsr.models.archs.restormer_arch import Restormer
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)
    # return cv2.cvtColor(cv2.imread(filepath), 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)
    # checkpoint = torch.load(weight_path)
    # model.load_network(weight_path)
    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)
    # img = np.float32(load_img(input_image_path)) / 255.0
    # img_t = torch.from_numpy(img).permute(2, 0, 1).unsqueeze(0).cuda()

    # pad到8的倍数
    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)