52Hz/HWMNet_lowlight_enhancement
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.HWMNet import HWMNet 15 16def main():17 parser = argparse.ArgumentParser(description='Demo Low-light Image enhancement')18 parser.add_argument('--input_dir', default='test/', type=str, help='Input images')19 parser.add_argument('--result_dir', default='result/', type=str, help='Directory for results')20 parser.add_argument('--weights',21 default='experiments/pretrained_models/LOL_enhancement_HWMNet.pth', type=str,22 help='Path to weights')23 24 args = parser.parse_args()25 26 inp_dir = args.input_dir27 out_dir = args.result_dir28 29 os.makedirs(out_dir, exist_ok=True)30 31 files = natsorted(glob.glob(os.path.join(inp_dir, '*')))32 33 if len(files) == 0:34 raise Exception(f"No files found at {inp_dir}")35 36 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')37 38 # Load corresponding models architecture and weights39 model = HWMNet(in_chn=3, wf=96, depth=4)40 model = model.to(device)41 model.eval()42 load_checkpoint(model, args.weights)43 44 45 mul = 1646 for file_ in files:47 img = Image.open(file_).convert('RGB')48 input_ = TF.to_tensor(img).unsqueeze(0).to(device)49 50 # Pad the input if not_multiple_of 851 h, w = input_.shape[2], input_.shape[3]52 H, W = ((h + mul) // mul) * mul, ((w + mul) // mul) * mul53 padh = H - h if h % mul != 0 else 054 padw = W - w if w % mul != 0 else 055 input_ = F.pad(input_, (0, padw, 0, padh), 'reflect')56 with torch.no_grad():57 restored = model(input_)58 59 restored = torch.clamp(restored, 0, 1)60 restored = restored[:, :, :h, :w]61 restored = restored.permute(0, 2, 3, 1).cpu().detach().numpy()62 restored = img_as_ubyte(restored[0])63 64 f = os.path.splitext(os.path.split(file_)[-1])[0]65 save_img((os.path.join(out_dir, f + '.png')), restored)66 67 68def save_img(filepath, img):69 cv2.imwrite(filepath, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))70 71 72def load_checkpoint(model, weights):73 checkpoint = torch.load(weights, map_location=torch.device('cpu'))74 try:75 model.load_state_dict(checkpoint["state_dict"])76 except:77 state_dict = checkpoint["state_dict"]78 new_state_dict = OrderedDict()79 for k, v in state_dict.items():80 name = k[7:] # remove `module.`81 new_state_dict[name] = v82 model.load_state_dict(new_state_dict)83 84 85if __name__ == '__main__':86 main()