Iceclear commited on
Commit
7931fc7
1 Parent(s): 736172d

Upload 3 files

Browse files
Files changed (3) hide show
  1. extract_subimage.py +182 -0
  2. generate_meta_info.py +25 -0
  3. meta_info_DFO.txt +0 -0
extract_subimage.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from multiprocessing import Pool
4
+ from os import path as osp
5
+
6
+ import cv2
7
+ import numpy as np
8
+ from tqdm import tqdm
9
+
10
+
11
+ def scandir(dir_path, suffix=None, recursive=False, full_path=False):
12
+ """Scan a directory to find the interested files.
13
+ Args:
14
+ dir_path (str): Path of the directory.
15
+ suffix (str | tuple(str), optional): File suffix that we are
16
+ interested in. Default: None.
17
+ recursive (bool, optional): If set to True, recursively scan the
18
+ directory. Default: False.
19
+ full_path (bool, optional): If set to True, include the dir_path.
20
+ Default: False.
21
+ Returns:
22
+ A generator for all the interested files with relative pathes.
23
+ """
24
+
25
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
26
+ raise TypeError('"suffix" must be a string or tuple of strings')
27
+
28
+ root = dir_path
29
+
30
+ def _scandir(dir_path, suffix, recursive):
31
+ for entry in os.scandir(dir_path):
32
+ if not entry.name.startswith('.') and entry.is_file():
33
+ if full_path:
34
+ return_path = entry.path
35
+ else:
36
+ return_path = osp.relpath(entry.path, root)
37
+
38
+ if suffix is None:
39
+ yield return_path
40
+ elif return_path.endswith(suffix):
41
+ yield return_path
42
+ else:
43
+ if recursive:
44
+ yield from _scandir(
45
+ entry.path, suffix=suffix, recursive=recursive)
46
+ else:
47
+ continue
48
+
49
+ return _scandir(dir_path, suffix=suffix, recursive=recursive)
50
+
51
+
52
+ def main():
53
+ """A multi-thread tool to crop large images to sub-images for faster IO.
54
+ It is used for DIV2K dataset.
55
+ opt (dict): Configuration dict. It contains:
56
+ n_thread (int): Thread number.
57
+ compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9.
58
+ A higher value means a smaller size and longer compression time.
59
+ Use 0 for faster CPU decompression. Default: 3, same in cv2.
60
+ input_folder (str): Path to the input folder.
61
+ save_folder (str): Path to save folder.
62
+ crop_size (int): Crop size.
63
+ step (int): Step for overlapped sliding window.
64
+ thresh_size (int): Threshold size. Patches whose size is lower
65
+ than thresh_size will be dropped.
66
+ Usage:
67
+ For each folder, run this script.
68
+ Typically, there are four folders to be processed for DIV2K dataset.
69
+ DIV2K_train_HR
70
+ DIV2K_train_LR_bicubic/X2
71
+ DIV2K_train_LR_bicubic/X3
72
+ DIV2K_train_LR_bicubic/X4
73
+ After process, each sub_folder should have the same number of
74
+ subimages.
75
+ Remember to modify opt configurations according to your settings.
76
+ """
77
+
78
+ opt = {}
79
+ opt['n_thread'] = 40
80
+ opt['compression_level'] = 3
81
+
82
+ # HR images
83
+ opt['input_folder'] = './GT'
84
+ opt['save_folder'] = './GT_sub'
85
+ opt['crop_size'] = 480
86
+ opt['step'] = 240
87
+ opt['thresh_size'] = 0
88
+ extract_subimages(opt)
89
+
90
+
91
+ def extract_subimages(opt):
92
+ """Crop images to subimages.
93
+ Args:
94
+ opt (dict): Configuration dict. It contains:
95
+ input_folder (str): Path to the input folder.
96
+ save_folder (str): Path to save folder.
97
+ n_thread (int): Thread number.
98
+ """
99
+ input_folder = opt['input_folder']
100
+ save_folder = opt['save_folder']
101
+ if not osp.exists(save_folder):
102
+ os.makedirs(save_folder)
103
+ print(f'mkdir {save_folder} ...', exist_okay=True)
104
+ else:
105
+ pass
106
+ # print(f'Folder {save_folder} already exists. Exit.')
107
+ # sys.exit(1)
108
+
109
+ img_list = list(scandir(input_folder, full_path=True))
110
+
111
+ pbar = tqdm(total=len(img_list), unit='image', desc='Extract')
112
+ pool = Pool(opt['n_thread'])
113
+ img_list = sorted(img_list)[-3:-2]
114
+ for path in img_list:
115
+ worker(path, opt)
116
+ raise NotImplementedError
117
+ pool.apply_async(
118
+ worker, args=(path, opt), callback=lambda arg: pbar.update(1))
119
+
120
+ pool.close()
121
+ pool.join()
122
+ pbar.close()
123
+ print('All processes done.')
124
+
125
+
126
+ def worker(path, opt):
127
+ """Worker for each process.
128
+ Args:
129
+ path (str): Image path.
130
+ opt (dict): Configuration dict. It contains:
131
+ crop_size (int): Crop size.
132
+ step (int): Step for overlapped sliding window.
133
+ thresh_size (int): Threshold size. Patches whose size is lower
134
+ than thresh_size will be dropped.
135
+ save_folder (str): Path to save folder.
136
+ compression_level (int): for cv2.IMWRITE_PNG_COMPRESSION.
137
+ Returns:
138
+ process_info (str): Process information displayed in progress bar.
139
+ """
140
+ crop_size = opt['crop_size']
141
+ step = opt['step']
142
+ thresh_size = opt['thresh_size']
143
+ img_name, extension = osp.splitext(osp.basename(path))
144
+
145
+ # remove the x2, x3, x4 and x8 in the filename for DIV2K
146
+ img_name = img_name.replace('x2',
147
+ '').replace('x3',
148
+ '').replace('x4',
149
+ '').replace('x8', '')
150
+
151
+ img = cv2.imread(path, cv2.IMREAD_UNCHANGED)
152
+
153
+ if img.ndim == 2:
154
+ h, w = img.shape
155
+ elif img.ndim == 3:
156
+ h, w, c = img.shape
157
+ else:
158
+ raise ValueError(f'Image ndim should be 2 or 3, but got {img.ndim}')
159
+
160
+ h_space = np.arange(0, h - crop_size + 1, step)
161
+ if h - (h_space[-1] + crop_size) > thresh_size:
162
+ h_space = np.append(h_space, h - crop_size)
163
+ w_space = np.arange(0, w - crop_size + 1, step)
164
+ if w - (w_space[-1] + crop_size) > thresh_size:
165
+ w_space = np.append(w_space, w - crop_size)
166
+
167
+ index = 0
168
+ for x in h_space:
169
+ for y in w_space:
170
+ index += 1
171
+ cropped_img = img[x:x + crop_size, y:y + crop_size, ...]
172
+ cropped_img = np.ascontiguousarray(cropped_img)
173
+ cv2.imwrite(
174
+ osp.join(opt['save_folder'],
175
+ f'{img_name}_s{index:03d}{extension}'), cropped_img,
176
+ [cv2.IMWRITE_PNG_COMPRESSION, opt['compression_level']])
177
+ process_info = f'Processing {img_name} ...'
178
+ return process_info
179
+
180
+
181
+ if __name__ == '__main__':
182
+ main()
generate_meta_info.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from os import path as osp
4
+
5
+ from PIL import Image
6
+
7
+ # print(len(sorted(glob.glob('GT_sub/*'))))
8
+ # raise NotImplementedError
9
+
10
+ with open('meta_info_DFO.txt', 'w') as f:
11
+ for idx, img_path in enumerate(sorted(glob.glob('GT_sub/*'))):
12
+ filename = osp.basename(img_path)
13
+ # img = Image.open(img_path) # lazy load
14
+ # width, height = img.size
15
+ # mode = img.mode
16
+ # if mode == 'RGB':
17
+ # n_channel = 3
18
+ # elif mode == 'L':
19
+ # n_channel = 1
20
+ # else:
21
+ # raise ValueError(f'Unsupported mode {mode}.')
22
+
23
+ info = f'{filename} (480,480,3)'
24
+ print(idx + 1, info)
25
+ f.write(f'{info}\n')
meta_info_DFO.txt ADDED
The diff for this file is too large to render. See raw diff