laoduanaaa commited on
Commit
780b7f4
·
verified ·
1 Parent(s): f8c6fa1

Upload folder using huggingface_hub

Browse files
Deblurring/Defocus_Deblurring/test.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:682fef5d911628688d1c458b30e8d24f71cb2840428a453839d817f413ba632a
3
+ size 2557794235
Deblurring/Defocus_Deblurring/train.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4da9af423ce94a2502081fb3079dd609b65ee93e2f9446b870598eb75ef6257
3
+ size 11825719078
Deblurring/Defocus_Deblurring/val.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6708225bcf33acefcd5f5fb78eb25bc8938a400aaee7d1202d0947713e5c8473
3
+ size 2551225246
Deblurring/Motion_Deblurring/test1.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb955bbd96b1521cff4686ae12624c47f5d9f9b24a0b49b575d2c03574accf73
3
+ size 2371837449
Deblurring/Motion_Deblurring/test2.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5fa86b7a18626530ad67271f27771bff9772818504317b1a177803df25df8b7
3
+ size 4231646359
Deblurring/Motion_Deblurring/test3.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4e9144c70865f991124cb651f5c8cff205e8ef12c8f9704938cd4464061d01e
3
+ size 586823244
Deblurring/Motion_Deblurring/test4.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d46a153320dd5475eb67e214af509fbec68f4b462c04539e718a9389b1b2398e
3
+ size 1154901621
Deblurring/Motion_Deblurring/train.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7f7286cb0d36d00f56964ef4bf13f7115be9814ab26f89c8328d36615e3701c
3
+ size 4114478505
Denoising/Gaussian/BSD400.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50c70ea87972273db53d726fbe272ce9e69edee27698d6c4a2b5671694f1841c
3
+ size 29250432
Denoising/Gaussian/DIV2K.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:949911a00c46d5edd41f724cf58a4ce34af9ee783b558e4b1689407f6e90c64b
3
+ size 3978341690
Denoising/Gaussian/Flickr2K.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a06bd1848ac0fc340ff05b6cd12a37ce59d90a93a43ab4f37663ccf4d5eda50
3
+ size 11638162386
Denoising/Gaussian/WaterlooED.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:deecd41ad235edcd52bb4e8986f63e60441f46c382b74cfe3aa52995c95a4f1f
3
+ size 2179349374
Denoising/Gaussian/test.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef4c0900b5fa84edb39d9aa8d82a3506bea4627ee11ee75fe373cdb3c3728435
3
+ size 188700167
Denoising/Real/test1.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1139c32896697e960159ae845070751e58894ddf607ebfe8f6d83ef012e2fbff
3
+ size 461780640
Denoising/Real/test2.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea016b2af631d345d68c8312a19ad60349015d3561653a635998892f0a5be928
3
+ size 10904384909
Denoising/Real/train.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aae8c8dd6643fc65454db60cc317d64accd8bea34187ea6c4aadcf772991446c
3
+ size 13233785522
Denoising/Real/val.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7cf6d4f07335c6a0f92d3ea191775aca62399b4eb37468ec66523c151fe82b90
3
+ size 293212394
Denoising/Real/val_lmdb.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:300364c5691e9ae208c784daa3e0455aefec95a7ecc636d56c656926d6de2d5f
3
+ size 310622810
Denoising/generate_patches_dfwb.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import numpy as np
4
+ from glob import glob
5
+ from natsort import natsorted
6
+ import os
7
+ from tqdm import tqdm
8
+ from pdb import set_trace as stx
9
+
10
+ src = 'Gaussian'
11
+ tar = 'Gaussian/train/DFWB'
12
+ os.makedirs(tar, exist_ok=True)
13
+
14
+ patch_size = 512
15
+ overlap = 96
16
+ p_max = 800
17
+
18
+
19
+ def save_files(file_):
20
+ path_contents = file_.split(os.sep)
21
+ foldname = path_contents[-2]
22
+ filename = os.path.splitext(path_contents[-1])[0]
23
+ img = cv2.imread(file_)
24
+ num_patch = 0
25
+ w, h = img.shape[:2]
26
+ if w > p_max and h > p_max:
27
+ w1 = list(np.arange(0, w-patch_size, patch_size-overlap, dtype=int))
28
+ h1 = list(np.arange(0, h-patch_size, patch_size-overlap, dtype=int))
29
+ w1.append(w-patch_size)
30
+ h1.append(h-patch_size)
31
+ for i in w1:
32
+ for j in h1:
33
+ num_patch += 1
34
+ patch = img[i:i+patch_size, j:j+patch_size,:]
35
+ savename = os.path.join(tar, foldname + '-' + filename + '-' + str(num_patch) + '.png')
36
+ cv2.imwrite(savename, patch)
37
+
38
+ else:
39
+ savename = os.path.join(tar, foldname + '-' + filename + '.png')
40
+ cv2.imwrite(savename, img)
41
+
42
+
43
+ files = []
44
+ for dataset in ['DIV2K', 'Flickr2K', 'WaterlooED', 'BSD400']:
45
+ df = natsorted(glob(os.path.join(src, dataset, '*.png')) + glob(os.path.join(src, dataset, '*.jpg')) + glob(os.path.join(src, dataset, '*.bmp')))
46
+ files.extend(df)
47
+
48
+ from joblib import Parallel, delayed
49
+ import multiprocessing
50
+ num_cores = 10
51
+ Parallel(n_jobs=num_cores)(delayed(save_files)(file_) for file_ in tqdm(files))
Denoising/generate_patches_sidd.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import numpy as np
4
+ from glob import glob
5
+ from natsort import natsorted
6
+ import os
7
+ from tqdm import tqdm
8
+ from pdb import set_trace as stx
9
+
10
+
11
+ src = 'Real/SIDD'
12
+ tar = 'Real/train/SIDD'
13
+
14
+ lr_tar = os.path.join(tar, 'input_crops')
15
+ hr_tar = os.path.join(tar, 'target_crops')
16
+
17
+ os.makedirs(lr_tar, exist_ok=True)
18
+ os.makedirs(hr_tar, exist_ok=True)
19
+
20
+ files = natsorted(glob(os.path.join(src, '*', '*.PNG')))
21
+
22
+ lr_files, hr_files = [], []
23
+ for file_ in files:
24
+ filename = os.path.split(file_)[-1]
25
+ if 'GT' in filename:
26
+ hr_files.append(file_)
27
+ if 'NOISY' in filename:
28
+ lr_files.append(file_)
29
+
30
+ files = [(i, j) for i, j in zip(lr_files, hr_files)]
31
+
32
+ patch_size = 512
33
+ overlap = 128
34
+ p_max = 0
35
+
36
+ def save_files(file_):
37
+ lr_file, hr_file = file_
38
+ filename = os.path.splitext(os.path.split(lr_file)[-1])[0]
39
+ lr_img = cv2.imread(lr_file)
40
+ hr_img = cv2.imread(hr_file)
41
+ num_patch = 0
42
+ w, h = lr_img.shape[:2]
43
+ if w > p_max and h > p_max:
44
+ w1 = list(np.arange(0, w-patch_size, patch_size-overlap, dtype=np.int))
45
+ h1 = list(np.arange(0, h-patch_size, patch_size-overlap, dtype=np.int))
46
+ w1.append(w-patch_size)
47
+ h1.append(h-patch_size)
48
+ for i in w1:
49
+ for j in h1:
50
+ num_patch += 1
51
+
52
+ lr_patch = lr_img[i:i+patch_size, j:j+patch_size,:]
53
+ hr_patch = hr_img[i:i+patch_size, j:j+patch_size,:]
54
+
55
+ lr_savename = os.path.join(lr_tar, filename + '-' + str(num_patch) + '.png')
56
+ hr_savename = os.path.join(hr_tar, filename + '-' + str(num_patch) + '.png')
57
+
58
+ cv2.imwrite(lr_savename, lr_patch)
59
+ cv2.imwrite(hr_savename, hr_patch)
60
+
61
+ else:
62
+ lr_savename = os.path.join(lr_tar, filename + '.png')
63
+ hr_savename = os.path.join(hr_tar, filename + '.png')
64
+
65
+ cv2.imwrite(lr_savename, lr_img)
66
+ cv2.imwrite(hr_savename, hr_img)
67
+
68
+ from joblib import Parallel, delayed
69
+ import multiprocessing
70
+ num_cores = 10
71
+ Parallel(n_jobs=num_cores)(delayed(save_files)(file_) for file_ in tqdm(files))
Denoising/generate_patches_sidd_nafnet.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Modified from NAFNet (https://github.com/megvii-research/NAFNet)
3
+ # ------------------------------------------------------------------------
4
+ import cv2
5
+ import numpy as np
6
+ import os
7
+ import sys
8
+ from multiprocessing import Pool
9
+ from os import path as osp
10
+ from tqdm import tqdm
11
+
12
+ # from basicsr.utils import scandir_SIDD
13
+ # from basicsr.utils.create_lmdb import create_lmdb_for_SIDD
14
+
15
+
16
+
17
+
18
+
19
+ # ------------------------------------------------------------------------
20
+ # Copyright (c) 2022 megvii-model. All Rights Reserved.
21
+ # ------------------------------------------------------------------------
22
+ # Modified from BasicSR (https://github.com/xinntao/BasicSR)
23
+ # Copyright 2018-2020 BasicSR Authors
24
+ # ------------------------------------------------------------------------
25
+
26
+ # Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/dist_utils.py # noqa: E501
27
+ import functools
28
+ import os
29
+ import subprocess
30
+ import torch
31
+ import torch.distributed as dist
32
+ import torch.multiprocessing as mp
33
+
34
+
35
+ def init_dist(launcher, backend='nccl', **kwargs):
36
+ if mp.get_start_method(allow_none=True) is None:
37
+ mp.set_start_method('spawn')
38
+ if launcher == 'pytorch':
39
+ _init_dist_pytorch(backend, **kwargs)
40
+ elif launcher == 'slurm':
41
+ _init_dist_slurm(backend, **kwargs)
42
+ else:
43
+ raise ValueError(f'Invalid launcher type: {launcher}')
44
+
45
+
46
+ def _init_dist_pytorch(backend, **kwargs):
47
+ rank = int(os.environ['RANK'])
48
+ num_gpus = torch.cuda.device_count()
49
+ torch.cuda.set_device(rank % num_gpus)
50
+ dist.init_process_group(backend=backend, **kwargs)
51
+
52
+
53
+ def _init_dist_slurm(backend, port=None):
54
+ """Initialize slurm distributed training environment.
55
+
56
+ If argument ``port`` is not specified, then the master port will be system
57
+ environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system
58
+ environment variable, then a default port ``29500`` will be used.
59
+
60
+ Args:
61
+ backend (str): Backend of torch.distributed.
62
+ port (int, optional): Master port. Defaults to None.
63
+ """
64
+ proc_id = int(os.environ['SLURM_PROCID'])
65
+ ntasks = int(os.environ['SLURM_NTASKS'])
66
+ node_list = os.environ['SLURM_NODELIST']
67
+ num_gpus = torch.cuda.device_count()
68
+ torch.cuda.set_device(proc_id % num_gpus)
69
+ addr = subprocess.getoutput(
70
+ f'scontrol show hostname {node_list} | head -n1')
71
+ # specify master port
72
+ if port is not None:
73
+ os.environ['MASTER_PORT'] = str(port)
74
+ elif 'MASTER_PORT' in os.environ:
75
+ pass # use MASTER_PORT in the environment variable
76
+ else:
77
+ # 29500 is torch.distributed default port
78
+ os.environ['MASTER_PORT'] = '29500'
79
+ os.environ['MASTER_ADDR'] = addr
80
+ os.environ['WORLD_SIZE'] = str(ntasks)
81
+ os.environ['LOCAL_RANK'] = str(proc_id % num_gpus)
82
+ os.environ['RANK'] = str(proc_id)
83
+ dist.init_process_group(backend=backend)
84
+
85
+
86
+ def get_dist_info():
87
+ if dist.is_available():
88
+ initialized = dist.is_initialized()
89
+ else:
90
+ initialized = False
91
+ if initialized:
92
+ rank = dist.get_rank()
93
+ world_size = dist.get_world_size()
94
+ else:
95
+ rank = 0
96
+ world_size = 1
97
+ return rank, world_size
98
+
99
+
100
+ def master_only(func):
101
+
102
+ @functools.wraps(func)
103
+ def wrapper(*args, **kwargs):
104
+ rank, _ = get_dist_info()
105
+ if rank == 0:
106
+ return func(*args, **kwargs)
107
+
108
+ return wrapper
109
+
110
+
111
+
112
+ # ------------------------------------------------------------------------
113
+ # Copyright (c) 2022 megvii-model. All Rights Reserved.
114
+ # ------------------------------------------------------------------------
115
+ # Modified from BasicSR (https://github.com/xinntao/BasicSR)
116
+ # Copyright 2018-2020 BasicSR Authors
117
+ # ------------------------------------------------------------------------
118
+ import datetime
119
+ import logging
120
+ import time
121
+
122
+ # from .dist_util import get_dist_info, master_only
123
+
124
+
125
+ class MessageLogger():
126
+ """Message logger for printing.
127
+
128
+ Args:
129
+ opt (dict): Config. It contains the following keys:
130
+ name (str): Exp name.
131
+ logger (dict): Contains 'print_freq' (str) for logger interval.
132
+ train (dict): Contains 'total_iter' (int) for total iters.
133
+ use_tb_logger (bool): Use tensorboard logger.
134
+ start_iter (int): Start iter. Default: 1.
135
+ tb_logger (obj:`tb_logger`): Tensorboard logger. Default: None.
136
+ """
137
+
138
+ def __init__(self, opt, start_iter=1, tb_logger=None):
139
+ self.exp_name = opt['name']
140
+ self.interval = opt['logger']['print_freq']
141
+ self.start_iter = start_iter
142
+ self.max_iters = opt['train']['total_iter']
143
+ self.use_tb_logger = opt['logger']['use_tb_logger']
144
+ self.tb_logger = tb_logger
145
+ self.start_time = time.time()
146
+ self.logger = get_root_logger()
147
+
148
+ @master_only
149
+ def __call__(self, log_vars):
150
+ """Format logging message.
151
+
152
+ Args:
153
+ log_vars (dict): It contains the following keys:
154
+ epoch (int): Epoch number.
155
+ iter (int): Current iter.
156
+ lrs (list): List for learning rates.
157
+
158
+ time (float): Iter time.
159
+ data_time (float): Data time for each iter.
160
+ """
161
+ # epoch, iter, learning rates
162
+ epoch = log_vars.pop('epoch')
163
+ current_iter = log_vars.pop('iter')
164
+ total_iter = log_vars.pop('total_iter')
165
+ lrs = log_vars.pop('lrs')
166
+
167
+ message = (f'[{self.exp_name[:5]}..][epoch:{epoch:3d}, '
168
+ f'iter:{current_iter:8,d}, lr:(')
169
+ for v in lrs:
170
+ message += f'{v:.3e},'
171
+ message += ')] '
172
+
173
+ # time and estimated time
174
+ if 'time' in log_vars.keys():
175
+ iter_time = log_vars.pop('time')
176
+ data_time = log_vars.pop('data_time')
177
+
178
+ total_time = time.time() - self.start_time
179
+ time_sec_avg = total_time / (current_iter - self.start_iter + 1)
180
+ eta_sec = time_sec_avg * (self.max_iters - current_iter - 1)
181
+ eta_str = str(datetime.timedelta(seconds=int(eta_sec)))
182
+ message += f'[eta: {eta_str}, '
183
+ message += f'time (data): {iter_time:.3f} ({data_time:.3f})] '
184
+
185
+ # other items, especially losses
186
+ for k, v in log_vars.items():
187
+ message += f'{k}: {v:.4e} '
188
+ # tensorboard logger
189
+ if self.use_tb_logger and 'debug' not in self.exp_name:
190
+ normed_step = 10000 * (current_iter / total_iter)
191
+ normed_step = int(normed_step)
192
+
193
+ if k.startswith('l_'):
194
+ self.tb_logger.add_scalar(f'losses/{k}', v, normed_step)
195
+ elif k.startswith('m_'):
196
+ self.tb_logger.add_scalar(f'metrics/{k}', v, normed_step)
197
+ else:
198
+ assert 1 == 0
199
+ # else:
200
+ # self.tb_logger.add_scalar(k, v, current_iter)
201
+ self.logger.info(message)
202
+
203
+
204
+ @master_only
205
+ def init_tb_logger(log_dir):
206
+ from torch.utils.tensorboard import SummaryWriter
207
+ tb_logger = SummaryWriter(log_dir=log_dir)
208
+ return tb_logger
209
+
210
+
211
+ @master_only
212
+ def init_wandb_logger(opt):
213
+ """We now only use wandb to sync tensorboard log."""
214
+ import wandb
215
+ logger = logging.getLogger('basicsr')
216
+
217
+ project = opt['logger']['wandb']['project']
218
+ resume_id = opt['logger']['wandb'].get('resume_id')
219
+ if resume_id:
220
+ wandb_id = resume_id
221
+ resume = 'allow'
222
+ logger.warning(f'Resume wandb logger with id={wandb_id}.')
223
+ else:
224
+ wandb_id = wandb.util.generate_id()
225
+ resume = 'never'
226
+
227
+ wandb.init(
228
+ id=wandb_id,
229
+ resume=resume,
230
+ name=opt['name'],
231
+ config=opt,
232
+ project=project,
233
+ sync_tensorboard=True)
234
+
235
+ logger.info(f'Use wandb logger with id={wandb_id}; project={project}.')
236
+
237
+
238
+ def get_root_logger(logger_name='basicsr',
239
+ log_level=logging.INFO,
240
+ log_file=None):
241
+ """Get the root logger.
242
+
243
+ The logger will be initialized if it has not been initialized. By default a
244
+ StreamHandler will be added. If `log_file` is specified, a FileHandler will
245
+ also be added.
246
+
247
+ Args:
248
+ logger_name (str): root logger name. Default: 'basicsr'.
249
+ log_file (str | None): The log filename. If specified, a FileHandler
250
+ will be added to the root logger.
251
+ log_level (int): The root logger level. Note that only the process of
252
+ rank 0 is affected, while other processes will set the level to
253
+ "Error" and be silent most of the time.
254
+
255
+ Returns:
256
+ logging.Logger: The root logger.
257
+ """
258
+ logger = logging.getLogger(logger_name)
259
+ # if the logger has been initialized, just return it
260
+ if logger.hasHandlers():
261
+ return logger
262
+
263
+ format_str = '%(asctime)s %(levelname)s: %(message)s'
264
+ logging.basicConfig(format=format_str, level=log_level)
265
+ rank, _ = get_dist_info()
266
+ if rank != 0:
267
+ logger.setLevel('ERROR')
268
+ elif log_file is not None:
269
+ file_handler = logging.FileHandler(log_file, 'w')
270
+ file_handler.setFormatter(logging.Formatter(format_str))
271
+ file_handler.setLevel(log_level)
272
+ logger.addHandler(file_handler)
273
+
274
+ return logger
275
+
276
+
277
+ # ------------------------------------------------------------------------
278
+ # Copyright (c) 2022 megvii-model. All Rights Reserved.
279
+ # ------------------------------------------------------------------------
280
+ # Modified from BasicSR (https://github.com/xinntao/BasicSR)
281
+ # Copyright 2018-2020 BasicSR Authors
282
+ # ------------------------------------------------------------------------
283
+ import numpy as np
284
+ import os
285
+ import random
286
+ import time
287
+ import torch
288
+ from os import path as osp
289
+
290
+ # from .dist_util import master_only
291
+ # from .logger import get_root_logger
292
+
293
+
294
+ def set_random_seed(seed):
295
+ """Set random seeds."""
296
+ random.seed(seed)
297
+ np.random.seed(seed)
298
+ torch.manual_seed(seed)
299
+ torch.cuda.manual_seed(seed)
300
+ torch.cuda.manual_seed_all(seed)
301
+
302
+
303
+ def get_time_str():
304
+ return time.strftime('%Y%m%d_%H%M%S', time.localtime())
305
+
306
+
307
+ def mkdir_and_rename(path):
308
+ """mkdirs. If path exists, rename it with timestamp and create a new one.
309
+
310
+ Args:
311
+ path (str): Folder path.
312
+ """
313
+ if osp.exists(path):
314
+ new_name = path + '_archived_' + get_time_str()
315
+ print(f'Path already exists. Rename it to {new_name}', flush=True)
316
+ os.rename(path, new_name)
317
+ os.makedirs(path, exist_ok=True)
318
+
319
+
320
+ @master_only
321
+ def make_exp_dirs(opt):
322
+ """Make dirs for experiments."""
323
+ path_opt = opt['path'].copy()
324
+ if opt['is_train']:
325
+ mkdir_and_rename(path_opt.pop('experiments_root'))
326
+ else:
327
+ mkdir_and_rename(path_opt.pop('results_root'))
328
+ for key, path in path_opt.items():
329
+ if ('strict_load' not in key) and ('pretrain_network'
330
+ not in key) and ('resume'
331
+ not in key):
332
+ os.makedirs(path, exist_ok=True)
333
+
334
+
335
+ def scandir(dir_path, suffix=None, recursive=False, full_path=False):
336
+ """Scan a directory to find the interested files.
337
+
338
+ Args:
339
+ dir_path (str): Path of the directory.
340
+ suffix (str | tuple(str), optional): File suffix that we are
341
+ interested in. Default: None.
342
+ recursive (bool, optional): If set to True, recursively scan the
343
+ directory. Default: False.
344
+ full_path (bool, optional): If set to True, include the dir_path.
345
+ Default: False.
346
+
347
+ Returns:
348
+ A generator for all the interested files with relative pathes.
349
+ """
350
+
351
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
352
+ raise TypeError('"suffix" must be a string or tuple of strings')
353
+
354
+ root = dir_path
355
+
356
+ def _scandir(dir_path, suffix, recursive):
357
+ for entry in os.scandir(dir_path):
358
+ if not entry.name.startswith('.') and entry.is_file():
359
+ if full_path:
360
+ return_path = entry.path
361
+ else:
362
+ return_path = osp.relpath(entry.path, root)
363
+
364
+ if suffix is None:
365
+ yield return_path
366
+ elif return_path.endswith(suffix):
367
+ yield return_path
368
+ else:
369
+ if recursive:
370
+ yield from _scandir(
371
+ entry.path, suffix=suffix, recursive=recursive)
372
+ else:
373
+ continue
374
+
375
+ return _scandir(dir_path, suffix=suffix, recursive=recursive)
376
+
377
+ def scandir_SIDD(dir_path, keywords=None, recursive=False, full_path=False):
378
+ """Scan a directory to find the interested files.
379
+
380
+ Args:
381
+ dir_path (str): Path of the directory.
382
+ keywords (str | tuple(str), optional): File keywords that we are
383
+ interested in. Default: None.
384
+ recursive (bool, optional): If set to True, recursively scan the
385
+ directory. Default: False.
386
+ full_path (bool, optional): If set to True, include the dir_path.
387
+ Default: False.
388
+
389
+ Returns:
390
+ A generator for all the interested files with relative pathes.
391
+ """
392
+
393
+ if (keywords is not None) and not isinstance(keywords, (str, tuple)):
394
+ raise TypeError('"keywords" must be a string or tuple of strings')
395
+
396
+ root = dir_path
397
+
398
+ def _scandir(dir_path, keywords, recursive):
399
+ for entry in os.scandir(dir_path):
400
+ if not entry.name.startswith('.') and entry.is_file():
401
+ if full_path:
402
+ return_path = entry.path
403
+ else:
404
+ return_path = osp.relpath(entry.path, root)
405
+
406
+ if keywords is None:
407
+ yield return_path
408
+ elif return_path.find(keywords) > 0:
409
+ yield return_path
410
+ else:
411
+ if recursive:
412
+ yield from _scandir(
413
+ entry.path, keywords=keywords, recursive=recursive)
414
+ else:
415
+ continue
416
+
417
+ return _scandir(dir_path, keywords=keywords, recursive=recursive)
418
+
419
+ def check_resume(opt, resume_iter):
420
+ """Check resume states and pretrain_network paths.
421
+
422
+ Args:
423
+ opt (dict): Options.
424
+ resume_iter (int): Resume iteration.
425
+ """
426
+ logger = get_root_logger()
427
+ if opt['path']['resume_state']:
428
+ # get all the networks
429
+ networks = [key for key in opt.keys() if key.startswith('network_')]
430
+ flag_pretrain = False
431
+ for network in networks:
432
+ if opt['path'].get(f'pretrain_{network}') is not None:
433
+ flag_pretrain = True
434
+ if flag_pretrain:
435
+ logger.warning(
436
+ 'pretrain_network path will be ignored during resuming.')
437
+ # set pretrained model paths
438
+ for network in networks:
439
+ name = f'pretrain_{network}'
440
+ basename = network.replace('network_', '')
441
+ if opt['path'].get('ignore_resume_networks') is None or (
442
+ basename not in opt['path']['ignore_resume_networks']):
443
+ opt['path'][name] = osp.join(
444
+ opt['path']['models'], f'net_{basename}_{resume_iter}.pth')
445
+ logger.info(f"Set {name} to {opt['path'][name]}")
446
+
447
+
448
+ def sizeof_fmt(size, suffix='B'):
449
+ """Get human readable file size.
450
+
451
+ Args:
452
+ size (int): File size.
453
+ suffix (str): Suffix. Default: 'B'.
454
+
455
+ Return:
456
+ str: Formated file siz.
457
+ """
458
+ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
459
+ if abs(size) < 1024.0:
460
+ return f'{size:3.1f} {unit}{suffix}'
461
+ size /= 1024.0
462
+ return f'{size:3.1f} Y{suffix}'
463
+
464
+
465
+
466
+
467
+ # ------------------------------------------------------------------------
468
+ # Copyright (c) 2022 megvii-model. All Rights Reserved.
469
+ # ------------------------------------------------------------------------
470
+ # Modified from BasicSR (https://github.com/xinntao/BasicSR)
471
+ # Copyright 2018-2020 BasicSR Authors
472
+ # ------------------------------------------------------------------------
473
+ import cv2
474
+ import lmdb
475
+ import sys
476
+ from multiprocessing import Pool
477
+ from os import path as osp
478
+ from tqdm import tqdm
479
+
480
+
481
+ def make_lmdb_from_imgs(data_path,
482
+ lmdb_path,
483
+ img_path_list,
484
+ keys,
485
+ batch=5000,
486
+ compress_level=1,
487
+ multiprocessing_read=False,
488
+ n_thread=40,
489
+ map_size=None):
490
+ """Make lmdb from images.
491
+
492
+ Contents of lmdb. The file structure is:
493
+ example.lmdb
494
+ ├── data.mdb
495
+ ├── lock.mdb
496
+ ├── meta_info.txt
497
+
498
+ The data.mdb and lock.mdb are standard lmdb files and you can refer to
499
+ https://lmdb.readthedocs.io/en/release/ for more details.
500
+
501
+ The meta_info.txt is a specified txt file to record the meta information
502
+ of our datasets. It will be automatically created when preparing
503
+ datasets by our provided dataset tools.
504
+ Each line in the txt file records 1)image name (with extension),
505
+ 2)image shape, and 3)compression level, separated by a white space.
506
+
507
+ For example, the meta information could be:
508
+ `000_00000000.png (720,1280,3) 1`, which means:
509
+ 1) image name (with extension): 000_00000000.png;
510
+ 2) image shape: (720,1280,3);
511
+ 3) compression level: 1
512
+
513
+ We use the image name without extension as the lmdb key.
514
+
515
+ If `multiprocessing_read` is True, it will read all the images to memory
516
+ using multiprocessing. Thus, your server needs to have enough memory.
517
+
518
+ Args:
519
+ data_path (str): Data path for reading images.
520
+ lmdb_path (str): Lmdb save path.
521
+ img_path_list (str): Image path list.
522
+ keys (str): Used for lmdb keys.
523
+ batch (int): After processing batch images, lmdb commits.
524
+ Default: 5000.
525
+ compress_level (int): Compress level when encoding images. Default: 1.
526
+ multiprocessing_read (bool): Whether use multiprocessing to read all
527
+ the images to memory. Default: False.
528
+ n_thread (int): For multiprocessing.
529
+ map_size (int | None): Map size for lmdb env. If None, use the
530
+ estimated size from images. Default: None
531
+ """
532
+
533
+ assert len(img_path_list) == len(keys), (
534
+ 'img_path_list and keys should have the same length, '
535
+ f'but got {len(img_path_list)} and {len(keys)}')
536
+ print(f'Create lmdb for {data_path}, save to {lmdb_path}...')
537
+ print(f'Total images: {len(img_path_list)}')
538
+ if not lmdb_path.endswith('.lmdb'):
539
+ raise ValueError("lmdb_path must end with '.lmdb'.")
540
+ if osp.exists(lmdb_path):
541
+ print(f'Folder {lmdb_path} already exists. Exit.')
542
+ sys.exit(1)
543
+
544
+ if multiprocessing_read:
545
+ # read all the images to memory (multiprocessing)
546
+ dataset = {} # use dict to keep the order for multiprocessing
547
+ shapes = {}
548
+ print(f'Read images with multiprocessing, #thread: {n_thread} ...')
549
+ pbar = tqdm(total=len(img_path_list), unit='image')
550
+
551
+ def callback(arg):
552
+ """get the image data and update pbar."""
553
+ key, dataset[key], shapes[key] = arg
554
+ pbar.update(1)
555
+ pbar.set_description(f'Read {key}')
556
+
557
+ pool = Pool(n_thread)
558
+ for path, key in zip(img_path_list, keys):
559
+ pool.apply_async(
560
+ read_img_worker,
561
+ args=(osp.join(data_path, path), key, compress_level),
562
+ callback=callback)
563
+ pool.close()
564
+ pool.join()
565
+ pbar.close()
566
+ print(f'Finish reading {len(img_path_list)} images.')
567
+
568
+ # create lmdb environment
569
+ if map_size is None:
570
+ # obtain data size for one image
571
+ img = cv2.imread(
572
+ osp.join(data_path, img_path_list[0]), cv2.IMREAD_UNCHANGED)
573
+ _, img_byte = cv2.imencode(
574
+ '.png', img, [cv2.IMWRITE_PNG_COMPRESSION, compress_level])
575
+ data_size_per_img = img_byte.nbytes
576
+ print('Data size per image is: ', data_size_per_img)
577
+ data_size = data_size_per_img * len(img_path_list)
578
+ map_size = data_size * 10
579
+
580
+ env = lmdb.open(lmdb_path, map_size=map_size)
581
+
582
+ # write data to lmdb
583
+ pbar = tqdm(total=len(img_path_list), unit='chunk')
584
+ txn = env.begin(write=True)
585
+ txt_file = open(osp.join(lmdb_path, 'meta_info.txt'), 'w')
586
+ for idx, (path, key) in enumerate(zip(img_path_list, keys)):
587
+ pbar.update(1)
588
+ pbar.set_description(f'Write {key}')
589
+ key_byte = key.encode('ascii')
590
+ if multiprocessing_read:
591
+ img_byte = dataset[key]
592
+ h, w, c = shapes[key]
593
+ else:
594
+ _, img_byte, img_shape = read_img_worker(
595
+ osp.join(data_path, path), key, compress_level)
596
+ h, w, c = img_shape
597
+
598
+ txn.put(key_byte, img_byte)
599
+ # write meta information
600
+ txt_file.write(f'{key}.png ({h},{w},{c}) {compress_level}\n')
601
+ if idx % batch == 0:
602
+ txn.commit()
603
+ txn = env.begin(write=True)
604
+ pbar.close()
605
+ txn.commit()
606
+ env.close()
607
+ txt_file.close()
608
+ print('\nFinish writing lmdb.')
609
+
610
+
611
+ def read_img_worker(path, key, compress_level):
612
+ """Read image worker.
613
+
614
+ Args:
615
+ path (str): Image path.
616
+ key (str): Image key.
617
+ compress_level (int): Compress level when encoding images.
618
+
619
+ Returns:
620
+ str: Image key.
621
+ byte: Image byte.
622
+ tuple[int]: Image shape.
623
+ """
624
+
625
+ img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
626
+ if img.ndim == 2:
627
+ h, w = img.shape
628
+ c = 1
629
+ else:
630
+ h, w, c = img.shape
631
+ _, img_byte = cv2.imencode('.png', img,
632
+ [cv2.IMWRITE_PNG_COMPRESSION, compress_level])
633
+ return (key, img_byte, (h, w, c))
634
+
635
+
636
+ class LmdbMaker():
637
+ """LMDB Maker.
638
+
639
+ Args:
640
+ lmdb_path (str): Lmdb save path.
641
+ map_size (int): Map size for lmdb env. Default: 1024 ** 4, 1TB.
642
+ batch (int): After processing batch images, lmdb commits.
643
+ Default: 5000.
644
+ compress_level (int): Compress level when encoding images. Default: 1.
645
+ """
646
+
647
+ def __init__(self,
648
+ lmdb_path,
649
+ map_size=1024**4,
650
+ batch=5000,
651
+ compress_level=1):
652
+ if not lmdb_path.endswith('.lmdb'):
653
+ raise ValueError("lmdb_path must end with '.lmdb'.")
654
+ if osp.exists(lmdb_path):
655
+ print(f'Folder {lmdb_path} already exists. Exit.')
656
+ sys.exit(1)
657
+
658
+ self.lmdb_path = lmdb_path
659
+ self.batch = batch
660
+ self.compress_level = compress_level
661
+ self.env = lmdb.open(lmdb_path, map_size=map_size)
662
+ self.txn = self.env.begin(write=True)
663
+ self.txt_file = open(osp.join(lmdb_path, 'meta_info.txt'), 'w')
664
+ self.counter = 0
665
+
666
+ def put(self, img_byte, key, img_shape):
667
+ self.counter += 1
668
+ key_byte = key.encode('ascii')
669
+ self.txn.put(key_byte, img_byte)
670
+ # write meta information
671
+ h, w, c = img_shape
672
+ self.txt_file.write(f'{key}.png ({h},{w},{c}) {self.compress_level}\n')
673
+ if self.counter % self.batch == 0:
674
+ self.txn.commit()
675
+ self.txn = self.env.begin(write=True)
676
+
677
+ def close(self):
678
+ self.txn.commit()
679
+ self.env.close()
680
+ self.txt_file.close()
681
+
682
+
683
+
684
+ # ------------------------------------------------------------------------
685
+ # Copyright (c) 2022 megvii-model. All Rights Reserved.
686
+ # ------------------------------------------------------------------------
687
+ # Modified from BasicSR (https://github.com/xinntao/BasicSR)
688
+ # Copyright 2018-2020 BasicSR Authors
689
+ # ------------------------------------------------------------------------
690
+ import argparse
691
+ from os import path as osp
692
+
693
+ # from basicsr.utils import scandir
694
+ # from basicsr.utils.lmdb_util import make_lmdb_from_imgs
695
+
696
+ def prepare_keys(folder_path, suffix='png'):
697
+ """Prepare image path list and keys for DIV2K dataset.
698
+
699
+ Args:
700
+ folder_path (str): Folder path.
701
+
702
+ Returns:
703
+ list[str]: Image path list.
704
+ list[str]: Key list.
705
+ """
706
+ print('Reading image path list ...')
707
+ img_path_list = sorted(
708
+ list(scandir(folder_path, suffix=suffix, recursive=False)))
709
+ keys = [img_path.split('.{}'.format(suffix))[0] for img_path in sorted(img_path_list)]
710
+
711
+ return img_path_list, keys
712
+
713
+ def create_lmdb_for_reds():
714
+ # folder_path = './datasets/REDS/val/sharp_300'
715
+ # lmdb_path = './datasets/REDS/val/sharp_300.lmdb'
716
+ # img_path_list, keys = prepare_keys(folder_path, 'png')
717
+ # make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
718
+ #
719
+ # folder_path = './datasets/REDS/val/blur_300'
720
+ # lmdb_path = './datasets/REDS/val/blur_300.lmdb'
721
+ # img_path_list, keys = prepare_keys(folder_path, 'jpg')
722
+ # make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
723
+
724
+ folder_path = './datasets/REDS/train/train_sharp'
725
+ lmdb_path = './datasets/REDS/train/train_sharp.lmdb'
726
+ img_path_list, keys = prepare_keys(folder_path, 'png')
727
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
728
+
729
+ folder_path = './datasets/REDS/train/train_blur_jpeg'
730
+ lmdb_path = './datasets/REDS/train/train_blur_jpeg.lmdb'
731
+ img_path_list, keys = prepare_keys(folder_path, 'jpg')
732
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
733
+
734
+
735
+ def create_lmdb_for_gopro():
736
+ folder_path = './datasets/GoPro/train/blur_crops'
737
+ lmdb_path = './datasets/GoPro/train/blur_crops.lmdb'
738
+
739
+ img_path_list, keys = prepare_keys(folder_path, 'png')
740
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
741
+
742
+ folder_path = './datasets/GoPro/train/sharp_crops'
743
+ lmdb_path = './datasets/GoPro/train/sharp_crops.lmdb'
744
+
745
+ img_path_list, keys = prepare_keys(folder_path, 'png')
746
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
747
+
748
+ # folder_path = './datasets/GoPro/test/target'
749
+ # lmdb_path = './datasets/GoPro/test/target.lmdb'
750
+
751
+ # img_path_list, keys = prepare_keys(folder_path, 'png')
752
+ # make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
753
+
754
+ # folder_path = './datasets/GoPro/test/input'
755
+ # lmdb_path = './datasets/GoPro/test/input.lmdb'
756
+
757
+ # img_path_list, keys = prepare_keys(folder_path, 'png')
758
+ # make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
759
+
760
+ def create_lmdb_for_rain13k():
761
+ folder_path = './datasets/Rain13k/train/input'
762
+ lmdb_path = './datasets/Rain13k/train/input.lmdb'
763
+
764
+ img_path_list, keys = prepare_keys(folder_path, 'jpg')
765
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
766
+
767
+ folder_path = './datasets/Rain13k/train/target'
768
+ lmdb_path = './datasets/Rain13k/train/target.lmdb'
769
+
770
+ img_path_list, keys = prepare_keys(folder_path, 'jpg')
771
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
772
+
773
+ def create_lmdb_for_SIDD():
774
+ folder_path = 'Real/train_nafnet/input_crops'
775
+ lmdb_path = 'Real/train_nafnet/input_crops.lmdb'
776
+
777
+ img_path_list, keys = prepare_keys(folder_path, 'PNG')
778
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
779
+
780
+ folder_path = 'Real/train_nafnet/gt_crops'
781
+ lmdb_path = 'Real/train_nafnet/gt_crops.lmdb'
782
+
783
+ img_path_list, keys = prepare_keys(folder_path, 'PNG')
784
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
785
+
786
+ #for val
787
+ '''
788
+
789
+ folder_path = './datasets/SIDD/val/input_crops'
790
+ lmdb_path = './datasets/SIDD/val/input_crops.lmdb'
791
+ mat_path = './datasets/SIDD/ValidationNoisyBlocksSrgb.mat'
792
+ if not osp.exists(folder_path):
793
+ os.makedirs(folder_path)
794
+ assert osp.exists(mat_path)
795
+ data = scio.loadmat(mat_path)['ValidationNoisyBlocksSrgb']
796
+ N, B, H ,W, C = data.shape
797
+ data = data.reshape(N*B, H, W, C)
798
+ for i in tqdm(range(N*B)):
799
+ cv2.imwrite(osp.join(folder_path, 'ValidationBlocksSrgb_{}.png'.format(i)), cv2.cvtColor(data[i,...], cv2.COLOR_RGB2BGR))
800
+ img_path_list, keys = prepare_keys(folder_path, 'png')
801
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
802
+
803
+ folder_path = './datasets/SIDD/val/gt_crops'
804
+ lmdb_path = './datasets/SIDD/val/gt_crops.lmdb'
805
+ mat_path = './datasets/SIDD/ValidationGtBlocksSrgb.mat'
806
+ if not osp.exists(folder_path):
807
+ os.makedirs(folder_path)
808
+ assert osp.exists(mat_path)
809
+ data = scio.loadmat(mat_path)['ValidationGtBlocksSrgb']
810
+ N, B, H ,W, C = data.shape
811
+ data = data.reshape(N*B, H, W, C)
812
+ for i in tqdm(range(N*B)):
813
+ cv2.imwrite(osp.join(folder_path, 'ValidationBlocksSrgb_{}.png'.format(i)), cv2.cvtColor(data[i,...], cv2.COLOR_RGB2BGR))
814
+ img_path_list, keys = prepare_keys(folder_path, 'png')
815
+ make_lmdb_from_imgs(folder_path, lmdb_path, img_path_list, keys)
816
+ '''
817
+
818
+
819
+
820
+
821
+
822
+
823
+
824
+
825
+
826
+
827
+
828
+
829
+
830
+
831
+
832
+
833
+
834
+
835
+
836
+
837
+
838
+
839
+
840
+
841
+
842
+
843
+
844
+
845
+
846
+
847
+
848
+
849
+
850
+
851
+
852
+
853
+
854
+
855
+
856
+
857
+ def main():
858
+ opt = {}
859
+ opt['n_thread'] = 20
860
+ opt['compression_level'] = 3
861
+
862
+ opt['input_folder'] = 'Real/SIDD'
863
+ opt['save_folder'] = 'Real/train_nafnet/input_crops'
864
+ opt['crop_size'] = 512
865
+ opt['step'] = 384
866
+ opt['thresh_size'] = 0
867
+ opt['keywords'] = '_NOISY'
868
+ extract_subimages(opt)
869
+
870
+ opt['save_folder'] = 'Real/train_nafnet/gt_crops'
871
+ opt['keywords'] = '_GT'
872
+ extract_subimages(opt)
873
+
874
+ create_lmdb_for_SIDD()
875
+
876
+
877
+ def extract_subimages(opt):
878
+ """Crop images to subimages.
879
+ Args:
880
+ opt (dict): Configuration dict. It contains:
881
+ input_folder (str): Path to the input folder.
882
+ save_folder (str): Path to save folder.
883
+ n_thread (int): Thread number.
884
+ """
885
+ input_folder = opt['input_folder']
886
+ save_folder = opt['save_folder']
887
+ if not osp.exists(save_folder):
888
+ os.makedirs(save_folder)
889
+ print(f'mkdir {save_folder} ...')
890
+ else:
891
+ print(f'Folder {save_folder} already exists. Exit.')
892
+ # sys.exit(1)
893
+
894
+ img_list = list(scandir_SIDD(input_folder, keywords=opt['keywords'], recursive=True, full_path=True))
895
+
896
+ pbar = tqdm(total=len(img_list), unit='image', desc='Extract')
897
+ pool = Pool(opt['n_thread'])
898
+ for path in img_list:
899
+ pool.apply_async(
900
+ worker, args=(path, opt), callback=lambda arg: pbar.update(1))
901
+ pool.close()
902
+ pool.join()
903
+ pbar.close()
904
+ print('All processes done.')
905
+
906
+
907
+ def worker(path, opt):
908
+ """Worker for each process.
909
+ Args:
910
+ path (str): Image path.
911
+ opt (dict): Configuration dict. It contains:
912
+ crop_size (int): Crop size.
913
+ step (int): Step for overlapped sliding window.
914
+ thresh_size (int): Threshold size. Patches whose size is lower
915
+ than thresh_size will be dropped.
916
+ save_folder (str): Path to save folder.
917
+ compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION.
918
+ Returns:
919
+ process_info (str): Process information displayed in progress bar.
920
+ """
921
+ crop_size = opt['crop_size']
922
+ step = opt['step']
923
+ thresh_size = opt['thresh_size']
924
+ img_name, extension = osp.splitext(osp.basename(path))
925
+
926
+ img_name = img_name.replace(opt['keywords'], '')
927
+
928
+ img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
929
+
930
+ if img.ndim == 2:
931
+ h, w = img.shape
932
+ elif img.ndim == 3:
933
+ h, w, c = img.shape
934
+ else:
935
+ raise ValueError(f'Image ndim should be 2 or 3, but got {img.ndim}')
936
+
937
+ h_space = np.arange(0, h - crop_size + 1, step)
938
+ if h - (h_space[-1] + crop_size) > thresh_size:
939
+ h_space = np.append(h_space, h - crop_size)
940
+ w_space = np.arange(0, w - crop_size + 1, step)
941
+ if w - (w_space[-1] + crop_size) > thresh_size:
942
+ w_space = np.append(w_space, w - crop_size)
943
+
944
+ index = 0
945
+ for x in h_space:
946
+ for y in w_space:
947
+ index += 1
948
+ cropped_img = img[x:x + crop_size, y:y + crop_size, ...]
949
+ cropped_img = np.ascontiguousarray(cropped_img)
950
+ cv2.imwrite(
951
+ osp.join(opt['save_folder'],
952
+ f'{img_name}_s{index:03d}{extension}'), cropped_img,
953
+ [cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']])
954
+ process_info = f'Processing {img_name} ...'
955
+ return process_info
956
+
957
+
958
+ if __name__ == '__main__':
959
+ main()
960
+ # ... make sidd to lmdb
Deraining/RainTrainL.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e41ca19e52c6951d65097c515a53ca34c92c3e1beb9c2dd67f7f92ded7e80632
3
+ size 119128495
Deraining/test.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5be86b39609c3fbd6b3f0cceb45aa98b06e38ad76d7fb85bcbe0eefc0a9d5311
3
+ size 1360310555
Deraining/train.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b999f61e7d7df1c2333d8a63a80b89fea2f75197dd9350428a174bcb9e193a5d
3
+ size 1163440376
Super_resolution/DF2K.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1106fb9796fa2a121ba3ac0478f5c6203d8c53a56e53be33c3a6e5cd1d6eff07
3
+ size 22872117208
Super_resolution/SR.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:630a9abd658668cc37473473d3415cf95e8890db894b2d2c103a31c913f04da2
3
+ size 472823749