52Hz/SRMNet_AWGN_denoising
13
1import argparse2import cv23import glob4import numpy as np5from collections import OrderedDict6from skimage import img_as_ubyte7import os8import torch9import requests10from PIL import Image11import torchvision.transforms.functional as TF12import torch.nn.functional as F13from natsort import natsorted14from model.SRMNet import SRMNet15 16def clean_folder(folder):17 for filename in os.listdir(folder):18 file_path = os.path.join(folder, filename)19 try:20 if os.path.isfile(file_path) or os.path.islink(file_path):21 os.unlink(file_path)22 elif os.path.isdir(file_path):23 shutil.rmtree(file_path)24 except Exception as e:25 print('Failed to delete %s. Reason: %s' % (file_path, e))26 27def save_img(filepath, img):28 cv2.imwrite(filepath, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))29 30 31def load_checkpoint(model, weights):32 checkpoint = torch.load(weights, map_location=torch.device('cpu'))33 try:34 model.load_state_dict(checkpoint["state_dict"])35 except:36 state_dict = checkpoint["state_dict"]37 new_state_dict = OrderedDict()38 for k, v in state_dict.items():39 name = k[7:] # remove `module.`40 new_state_dict[name] = v41 model.load_state_dict(new_state_dict)42 43 44def main():45 parser = argparse.ArgumentParser(description='Demo Image Denoising')46 parser.add_argument('--input_dir', default='test', type=str, help='Input images')47 parser.add_argument('--result_dir', default='result', type=str, help='Directory for results')48 parser.add_argument('--weights',49 default='experiments/pretrained_models/AWGN_denoising_SRMNet.pth', type=str,50 help='Path to weights')51 52 args = parser.parse_args()53 54 inp_dir = args.input_dir55 out_dir = args.result_dir56 57 os.makedirs(out_dir, exist_ok=True)58 59 files = natsorted(glob.glob(os.path.join(inp_dir, '*')))60 61 if len(files) == 0:62 raise Exception(f"No files found at {inp_dir}")63 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')65 66 # Load corresponding models architecture and weights67 model = SRMNet()68 model = model.to(device)69 model.eval()70 load_checkpoint(model, args.weights)71 72 73 mul = 1674 for file_ in files:75 img = Image.open(file_).convert('RGB')76 input_ = TF.to_tensor(img).unsqueeze(0).to(device)77 78 # Pad the input if not_multiple_of 879 h, w = input_.shape[2], input_.shape[3]80 H, W = ((h + mul) // mul) * mul, ((w + mul) // mul) * mul81 padh = H - h if h % mul != 0 else 082 padw = W - w if w % mul != 0 else 083 input_ = F.pad(input_, (0, padw, 0, padh), 'reflect')84 with torch.no_grad():85 restored = model(input_)86 87 restored = torch.clamp(restored, 0, 1)88 restored = restored[:, :, :h, :w]89 restored = restored.permute(0, 2, 3, 1).cpu().detach().numpy()90 restored = img_as_ubyte(restored[0])91 92 f = os.path.splitext(os.path.split(file_)[-1])[0]93 save_img((os.path.join(out_dir, f + '.png')), restored)94 clean_folder(inp_dir)95 96 97if __name__ == '__main__':98 main()