wzhouxiff commited on
Commit
d596782
1 Parent(s): b6e96dd

Create realesrgan.py

Browse files
Files changed (1) hide show
  1. realesrgan.py +350 -0
realesrgan.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import math
3
+ import numpy as np
4
+ import os
5
+ import queue
6
+ import threading
7
+ import torch
8
+
9
+ from torch.nn import functional as F
10
+
11
+ import requests
12
+ from torch.hub import download_url_to_file, get_dir
13
+
14
+ from urllib.parse import urlparse
15
+
16
+ from .misc import sizeof_fmt
17
+
18
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+
20
+ def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
21
+ """Load file form http url, will download models if necessary.
22
+
23
+ Reference: https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py
24
+
25
+ Args:
26
+ url (str): URL to be downloaded.
27
+ model_dir (str): The path to save the downloaded model. Should be a full path. If None, use pytorch hub_dir.
28
+ Default: None.
29
+ progress (bool): Whether to show the download progress. Default: True.
30
+ file_name (str): The downloaded file name. If None, use the file name in the url. Default: None.
31
+
32
+ Returns:
33
+ str: The path to the downloaded file.
34
+ """
35
+ if model_dir is None: # use the pytorch hub_dir
36
+ hub_dir = get_dir()
37
+ model_dir = os.path.join(hub_dir, 'checkpoints')
38
+
39
+ os.makedirs(model_dir, exist_ok=True)
40
+
41
+ parts = urlparse(url)
42
+ filename = os.path.basename(parts.path)
43
+ if file_name is not None:
44
+ filename = file_name
45
+ cached_file = os.path.abspath(os.path.join(model_dir, filename))
46
+ if not os.path.exists(cached_file):
47
+ print(f'Downloading: "{url}" to {cached_file}\n')
48
+ download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
49
+ return cached_file
50
+
51
+ class RealESRGANer():
52
+ """A helper class for upsampling images with RealESRGAN.
53
+
54
+ Args:
55
+ scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4.
56
+ model_path (str): The path to the pretrained model. It can be urls (will first download it automatically).
57
+ model (nn.Module): The defined network. Default: None.
58
+ tile (int): As too large images result in the out of GPU memory issue, so this tile option will first crop
59
+ input images into tiles, and then process each of them. Finally, they will be merged into one image.
60
+ 0 denotes for do not use tile. Default: 0.
61
+ tile_pad (int): The pad size for each tile, to remove border artifacts. Default: 10.
62
+ pre_pad (int): Pad the input images to avoid border artifacts. Default: 10.
63
+ half (float): Whether to use half precision during inference. Default: False.
64
+ """
65
+
66
+ def __init__(self,
67
+ scale,
68
+ model_path,
69
+ dni_weight=None,
70
+ model=None,
71
+ tile=0,
72
+ tile_pad=10,
73
+ pre_pad=10,
74
+ half=False,
75
+ device=None,
76
+ gpu_id=None):
77
+ self.scale = scale
78
+ self.tile_size = tile
79
+ self.tile_pad = tile_pad
80
+ self.pre_pad = pre_pad
81
+ self.mod_scale = None
82
+ self.half = half
83
+
84
+ # initialize model
85
+ if gpu_id:
86
+ self.device = torch.device(
87
+ f'cuda:{gpu_id}' if torch.cuda.is_available() else 'cpu') if device is None else device
88
+ else:
89
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') if device is None else device
90
+
91
+ if isinstance(model_path, list):
92
+ # dni
93
+ assert len(model_path) == len(dni_weight), 'model_path and dni_weight should have the save length.'
94
+ loadnet = self.dni(model_path[0], model_path[1], dni_weight)
95
+ else:
96
+ # if the model_path starts with https, it will first download models to the folder: weights
97
+ if model_path.startswith('https://'):
98
+ model_path = load_file_from_url(
99
+ url=model_path, model_dir=os.path.join(ROOT_DIR, 'weights'), progress=True, file_name=None)
100
+ loadnet = torch.load(model_path, map_location=torch.device('cpu'))
101
+
102
+ # prefer to use params_ema
103
+ if 'params_ema' in loadnet:
104
+ keyname = 'params_ema'
105
+ else:
106
+ keyname = 'params'
107
+ model.load_state_dict(loadnet[keyname], strict=True)
108
+
109
+ model.eval()
110
+ self.model = model.to(self.device)
111
+ if self.half:
112
+ self.model = self.model.half()
113
+
114
+ def dni(self, net_a, net_b, dni_weight, key='params', loc='cpu'):
115
+ """Deep network interpolation.
116
+
117
+ ``Paper: Deep Network Interpolation for Continuous Imagery Effect Transition``
118
+ """
119
+ net_a = torch.load(net_a, map_location=torch.device(loc))
120
+ net_b = torch.load(net_b, map_location=torch.device(loc))
121
+ for k, v_a in net_a[key].items():
122
+ net_a[key][k] = dni_weight[0] * v_a + dni_weight[1] * net_b[key][k]
123
+ return net_a
124
+
125
+ def pre_process(self, img):
126
+ """Pre-process, such as pre-pad and mod pad, so that the images can be divisible
127
+ """
128
+ img = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()
129
+ self.img = img.unsqueeze(0).to(self.device)
130
+ if self.half:
131
+ self.img = self.img.half()
132
+
133
+ # pre_pad
134
+ if self.pre_pad != 0:
135
+ self.img = F.pad(self.img, (0, self.pre_pad, 0, self.pre_pad), 'reflect')
136
+ # mod pad for divisible borders
137
+ if self.scale == 2:
138
+ self.mod_scale = 2
139
+ elif self.scale == 1:
140
+ self.mod_scale = 4
141
+ if self.mod_scale is not None:
142
+ self.mod_pad_h, self.mod_pad_w = 0, 0
143
+ _, _, h, w = self.img.size()
144
+ if (h % self.mod_scale != 0):
145
+ self.mod_pad_h = (self.mod_scale - h % self.mod_scale)
146
+ if (w % self.mod_scale != 0):
147
+ self.mod_pad_w = (self.mod_scale - w % self.mod_scale)
148
+ self.img = F.pad(self.img, (0, self.mod_pad_w, 0, self.mod_pad_h), 'reflect')
149
+
150
+ def process(self):
151
+ # model inference
152
+ self.output = self.model(self.img)
153
+
154
+ def tile_process(self):
155
+ """It will first crop input images to tiles, and then process each tile.
156
+ Finally, all the processed tiles are merged into one images.
157
+
158
+ Modified from: https://github.com/ata4/esrgan-launcher
159
+ """
160
+ batch, channel, height, width = self.img.shape
161
+ output_height = height * self.scale
162
+ output_width = width * self.scale
163
+ output_shape = (batch, channel, output_height, output_width)
164
+
165
+ # start with black image
166
+ self.output = self.img.new_zeros(output_shape)
167
+ tiles_x = math.ceil(width / self.tile_size)
168
+ tiles_y = math.ceil(height / self.tile_size)
169
+
170
+ # loop over all tiles
171
+ for y in range(tiles_y):
172
+ for x in range(tiles_x):
173
+ # extract tile from input image
174
+ ofs_x = x * self.tile_size
175
+ ofs_y = y * self.tile_size
176
+ # input tile area on total image
177
+ input_start_x = ofs_x
178
+ input_end_x = min(ofs_x + self.tile_size, width)
179
+ input_start_y = ofs_y
180
+ input_end_y = min(ofs_y + self.tile_size, height)
181
+
182
+ # input tile area on total image with padding
183
+ input_start_x_pad = max(input_start_x - self.tile_pad, 0)
184
+ input_end_x_pad = min(input_end_x + self.tile_pad, width)
185
+ input_start_y_pad = max(input_start_y - self.tile_pad, 0)
186
+ input_end_y_pad = min(input_end_y + self.tile_pad, height)
187
+
188
+ # input tile dimensions
189
+ input_tile_width = input_end_x - input_start_x
190
+ input_tile_height = input_end_y - input_start_y
191
+ tile_idx = y * tiles_x + x + 1
192
+ input_tile = self.img[:, :, input_start_y_pad:input_end_y_pad, input_start_x_pad:input_end_x_pad]
193
+
194
+ # upscale tile
195
+ try:
196
+ with torch.no_grad():
197
+ output_tile = self.model(input_tile)
198
+ except RuntimeError as error:
199
+ print('Error', error)
200
+ print(f'\tTile {tile_idx}/{tiles_x * tiles_y}')
201
+
202
+ # output tile area on total image
203
+ output_start_x = input_start_x * self.scale
204
+ output_end_x = input_end_x * self.scale
205
+ output_start_y = input_start_y * self.scale
206
+ output_end_y = input_end_y * self.scale
207
+
208
+ # output tile area without padding
209
+ output_start_x_tile = (input_start_x - input_start_x_pad) * self.scale
210
+ output_end_x_tile = output_start_x_tile + input_tile_width * self.scale
211
+ output_start_y_tile = (input_start_y - input_start_y_pad) * self.scale
212
+ output_end_y_tile = output_start_y_tile + input_tile_height * self.scale
213
+
214
+ # put tile into output image
215
+ self.output[:, :, output_start_y:output_end_y,
216
+ output_start_x:output_end_x] = output_tile[:, :, output_start_y_tile:output_end_y_tile,
217
+ output_start_x_tile:output_end_x_tile]
218
+
219
+ def post_process(self):
220
+ # remove extra pad
221
+ if self.mod_scale is not None:
222
+ _, _, h, w = self.output.size()
223
+ self.output = self.output[:, :, 0:h - self.mod_pad_h * self.scale, 0:w - self.mod_pad_w * self.scale]
224
+ # remove prepad
225
+ if self.pre_pad != 0:
226
+ _, _, h, w = self.output.size()
227
+ self.output = self.output[:, :, 0:h - self.pre_pad * self.scale, 0:w - self.pre_pad * self.scale]
228
+ return self.output
229
+
230
+ @torch.no_grad()
231
+ def enhance(self, img, outscale=None, alpha_upsampler='realesrgan'):
232
+ h_input, w_input = img.shape[0:2]
233
+ # img: numpy
234
+ img = img.astype(np.float32)
235
+ if np.max(img) > 256: # 16-bit image
236
+ max_range = 65535
237
+ print('\tInput is a 16-bit image')
238
+ else:
239
+ max_range = 255
240
+ img = img / max_range
241
+ if len(img.shape) == 2: # gray image
242
+ img_mode = 'L'
243
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
244
+ elif img.shape[2] == 4: # RGBA image with alpha channel
245
+ img_mode = 'RGBA'
246
+ alpha = img[:, :, 3]
247
+ img = img[:, :, 0:3]
248
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
249
+ if alpha_upsampler == 'realesrgan':
250
+ alpha = cv2.cvtColor(alpha, cv2.COLOR_GRAY2RGB)
251
+ else:
252
+ img_mode = 'RGB'
253
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
254
+
255
+ # ------------------- process image (without the alpha channel) ------------------- #
256
+ self.pre_process(img)
257
+ if self.tile_size > 0:
258
+ self.tile_process()
259
+ else:
260
+ self.process()
261
+ output_img = self.post_process()
262
+ output_img = output_img.data.squeeze().float().cpu().clamp_(0, 1).numpy()
263
+ output_img = np.transpose(output_img[[2, 1, 0], :, :], (1, 2, 0))
264
+ if img_mode == 'L':
265
+ output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2GRAY)
266
+
267
+ # ------------------- process the alpha channel if necessary ------------------- #
268
+ if img_mode == 'RGBA':
269
+ if alpha_upsampler == 'realesrgan':
270
+ self.pre_process(alpha)
271
+ if self.tile_size > 0:
272
+ self.tile_process()
273
+ else:
274
+ self.process()
275
+ output_alpha = self.post_process()
276
+ output_alpha = output_alpha.data.squeeze().float().cpu().clamp_(0, 1).numpy()
277
+ output_alpha = np.transpose(output_alpha[[2, 1, 0], :, :], (1, 2, 0))
278
+ output_alpha = cv2.cvtColor(output_alpha, cv2.COLOR_BGR2GRAY)
279
+ else: # use the cv2 resize for alpha channel
280
+ h, w = alpha.shape[0:2]
281
+ output_alpha = cv2.resize(alpha, (w * self.scale, h * self.scale), interpolation=cv2.INTER_LINEAR)
282
+
283
+ # merge the alpha channel
284
+ output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2BGRA)
285
+ output_img[:, :, 3] = output_alpha
286
+
287
+ # ------------------------------ return ------------------------------ #
288
+ if max_range == 65535: # 16-bit image
289
+ output = (output_img * 65535.0).round().astype(np.uint16)
290
+ else:
291
+ output = (output_img * 255.0).round().astype(np.uint8)
292
+
293
+ if outscale is not None and outscale != float(self.scale):
294
+ output = cv2.resize(
295
+ output, (
296
+ int(w_input * outscale),
297
+ int(h_input * outscale),
298
+ ), interpolation=cv2.INTER_LANCZOS4)
299
+
300
+ return output, img_mode
301
+
302
+
303
+ class PrefetchReader(threading.Thread):
304
+ """Prefetch images.
305
+
306
+ Args:
307
+ img_list (list[str]): A image list of image paths to be read.
308
+ num_prefetch_queue (int): Number of prefetch queue.
309
+ """
310
+
311
+ def __init__(self, img_list, num_prefetch_queue):
312
+ super().__init__()
313
+ self.que = queue.Queue(num_prefetch_queue)
314
+ self.img_list = img_list
315
+
316
+ def run(self):
317
+ for img_path in self.img_list:
318
+ img = cv2.imread(img_path, cv2.IMREAD_UNCHANGED)
319
+ self.que.put(img)
320
+
321
+ self.que.put(None)
322
+
323
+ def __next__(self):
324
+ next_item = self.que.get()
325
+ if next_item is None:
326
+ raise StopIteration
327
+ return next_item
328
+
329
+ def __iter__(self):
330
+ return self
331
+
332
+
333
+ class IOConsumer(threading.Thread):
334
+
335
+ def __init__(self, opt, que, qid):
336
+ super().__init__()
337
+ self._queue = que
338
+ self.qid = qid
339
+ self.opt = opt
340
+
341
+ def run(self):
342
+ while True:
343
+ msg = self._queue.get()
344
+ if isinstance(msg, str) and msg == 'quit':
345
+ break
346
+
347
+ output = msg['output']
348
+ save_path = msg['save_path']
349
+ cv2.imwrite(save_path, output)
350
+ print(f'IO worker {self.qid} is done.')