Team Ai
Apppublic

52Hz/CMFNet_deraindrop

sourceHugging Faceupdated 2y agoView on Hugging Face
13likes
main_test_CMFNet.py101 linesDownload Raw Back to root
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.CMFNet import CMFNet15 16 17def save_img(filepath, img):18    cv2.imwrite(filepath, cv2.cvtColor(img, cv2.COLOR_RGB2BGR))19 20 21def load_checkpoint(model, weights):22    checkpoint = torch.load(weights, map_location=torch.device('cpu'))23    try:24        model.load_state_dict(checkpoint["state_dict"])25    except:26        state_dict = checkpoint["state_dict"]27        new_state_dict = OrderedDict()28        for k, v in state_dict.items():29            name = k[7:]  # remove `module.`30            new_state_dict[name] = v31        model.load_state_dict(new_state_dict)32        33def clean_folder(folder):34    for filename in os.listdir(folder):35        file_path = os.path.join(folder, filename)36        try:37            if os.path.isfile(file_path) or os.path.islink(file_path):38                os.unlink(file_path)39            elif os.path.isdir(file_path):40                shutil.rmtree(file_path)41        except Exception as e:42            print('Failed to delete %s. Reason: %s' % (file_path, e))43            44 45def main():46    parser = argparse.ArgumentParser(description='Demo Image Deraindrop')47    parser.add_argument('--input_dir', default='test/', type=str, help='Input images')48    parser.add_argument('--result_dir', default='results/', type=str, help='Directory for results')49    parser.add_argument('--weights',50                        default='experiments/pretrained_models/deraindrop_model.pth', type=str,51                        help='Path to weights')52 53    args = parser.parse_args()54 55    inp_dir = args.input_dir56    out_dir = args.result_dir57 58    os.makedirs(out_dir, exist_ok=True)59 60    files = natsorted(glob.glob(os.path.join(inp_dir, '*')))61 62    if len(files) == 0:63        raise Exception(f"No files found at {inp_dir}")64 65    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')66 67    # Load corresponding models architecture and weights68    model = CMFNet()69    model = model.to(device)70    model.eval()71    load_checkpoint(model, args.weights)72    73 74    mul = 875    for file_ in files:76        img = Image.open(file_).convert('RGB')77        input_ = TF.to_tensor(img).unsqueeze(0).to(device)78 79        # Pad the input if not_multiple_of 880        h, w = input_.shape[2], input_.shape[3]81        H, W = ((h + mul) // mul) * mul, ((w + mul) // mul) * mul82        padh = H - h if h % mul != 0 else 083        padw = W - w if w % mul != 0 else 084        input_ = F.pad(input_, (0, padw, 0, padh), 'reflect')85        86        with torch.no_grad():87            restored = model(input_)88            89        restored = torch.clamp(restored, 0, 1)90        restored = restored[:, :, :h, :w]91        restored = restored.permute(0, 2, 3, 1).cpu().detach().numpy()92        restored = img_as_ubyte(restored[0])93 94        f = os.path.splitext(os.path.split(file_)[-1])[0]95        save_img((os.path.join(out_dir, f + '.png')), restored)96 97    clean_folder(inp_dir)98 99 100if __name__ == '__main__':101    main()