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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import random
4
+ import numpy as np
5
+ import torch
6
+ import cv2
7
+ from torchvision.utils import make_grid
8
+ from datetime import datetime
9
+ # import torchvision.transforms as transforms
10
+ import matplotlib.pyplot as plt
11
+ from mpl_toolkits.mplot3d import Axes3D
12
+
13
+
14
+ '''
15
+ # --------------------------------------------
16
+ # Kai Zhang (github: https://github.com/cszn)
17
+ # 03/Mar/2019
18
+ # --------------------------------------------
19
+ # https://github.com/twhui/SRGAN-pyTorch
20
+ # https://github.com/xinntao/BasicSR
21
+ # --------------------------------------------
22
+ '''
23
+
24
+
25
+ IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.tif']
26
+
27
+
28
+ def is_image_file(filename):
29
+ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
30
+
31
+
32
+ def get_timestamp():
33
+ return datetime.now().strftime('%y%m%d-%H%M%S')
34
+
35
+
36
+ def imshow(x, title=None, cbar=False, figsize=None):
37
+ plt.figure(figsize=figsize)
38
+ plt.imshow(np.squeeze(x), interpolation='nearest', cmap='gray')
39
+ if title:
40
+ plt.title(title)
41
+ if cbar:
42
+ plt.colorbar()
43
+ plt.show()
44
+
45
+
46
+ def surf(Z, cmap='rainbow', figsize=None):
47
+ plt.figure(figsize=figsize)
48
+ ax3 = plt.axes(projection='3d')
49
+
50
+ w, h = Z.shape[:2]
51
+ xx = np.arange(0,w,1)
52
+ yy = np.arange(0,h,1)
53
+ X, Y = np.meshgrid(xx, yy)
54
+ ax3.plot_surface(X,Y,Z,cmap=cmap)
55
+ #ax3.contour(X,Y,Z, zdim='z',offset=-2,cmap=cmap)
56
+ plt.show()
57
+
58
+
59
+ '''
60
+ # --------------------------------------------
61
+ # get image pathes
62
+ # --------------------------------------------
63
+ '''
64
+
65
+
66
+ def get_image_paths(dataroot):
67
+ paths = None # return None if dataroot is None
68
+ if dataroot is not None:
69
+ paths = sorted(_get_paths_from_images(dataroot))
70
+ return paths
71
+
72
+
73
+ def _get_paths_from_images(path):
74
+ assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)
75
+ images = []
76
+ for dirpath, _, fnames in sorted(os.walk(path)):
77
+ for fname in sorted(fnames):
78
+ if is_image_file(fname):
79
+ img_path = os.path.join(dirpath, fname)
80
+ images.append(img_path)
81
+ assert images, '{:s} has no valid image file'.format(path)
82
+ return images
83
+
84
+
85
+ '''
86
+ # --------------------------------------------
87
+ # split large images into small images
88
+ # --------------------------------------------
89
+ '''
90
+
91
+
92
+ def patches_from_image(img, p_size=512, p_overlap=64, p_max=800):
93
+ w, h = img.shape[:2]
94
+ patches = []
95
+ if w > p_max and h > p_max:
96
+ w1 = list(np.arange(0, w-p_size, p_size-p_overlap, dtype=np.int))
97
+ h1 = list(np.arange(0, h-p_size, p_size-p_overlap, dtype=np.int))
98
+ w1.append(w-p_size)
99
+ h1.append(h-p_size)
100
+ # print(w1)
101
+ # print(h1)
102
+ for i in w1:
103
+ for j in h1:
104
+ patches.append(img[i:i+p_size, j:j+p_size,:])
105
+ else:
106
+ patches.append(img)
107
+
108
+ return patches
109
+
110
+
111
+ def imssave(imgs, img_path):
112
+ """
113
+ imgs: list, N images of size WxHxC
114
+ """
115
+ img_name, ext = os.path.splitext(os.path.basename(img_path))
116
+ for i, img in enumerate(imgs):
117
+ if img.ndim == 3:
118
+ img = img[:, :, [2, 1, 0]]
119
+ new_path = os.path.join(os.path.dirname(img_path), img_name+str('_{:04d}'.format(i))+'.png')
120
+ cv2.imwrite(new_path, img)
121
+
122
+
123
+ def split_imageset(original_dataroot, taget_dataroot, n_channels=3, p_size=512, p_overlap=96, p_max=800):
124
+ """
125
+ split the large images from original_dataroot into small overlapped images with size (p_size)x(p_size),
126
+ and save them into taget_dataroot; only the images with larger size than (p_max)x(p_max)
127
+ will be splitted.
128
+
129
+ Args:
130
+ original_dataroot:
131
+ taget_dataroot:
132
+ p_size: size of small images
133
+ p_overlap: patch size in training is a good choice
134
+ p_max: images with smaller size than (p_max)x(p_max) keep unchanged.
135
+ """
136
+ paths = get_image_paths(original_dataroot)
137
+ for img_path in paths:
138
+ # img_name, ext = os.path.splitext(os.path.basename(img_path))
139
+ img = imread_uint(img_path, n_channels=n_channels)
140
+ patches = patches_from_image(img, p_size, p_overlap, p_max)
141
+ imssave(patches, os.path.join(taget_dataroot, os.path.basename(img_path)))
142
+ #if original_dataroot == taget_dataroot:
143
+ #del img_path
144
+
145
+ '''
146
+ # --------------------------------------------
147
+ # makedir
148
+ # --------------------------------------------
149
+ '''
150
+
151
+
152
+ def mkdir(path):
153
+ if not os.path.exists(path):
154
+ os.makedirs(path)
155
+
156
+
157
+ def mkdirs(paths):
158
+ if isinstance(paths, str):
159
+ mkdir(paths)
160
+ else:
161
+ for path in paths:
162
+ mkdir(path)
163
+
164
+
165
+ def mkdir_and_rename(path):
166
+ if os.path.exists(path):
167
+ new_name = path + '_archived_' + get_timestamp()
168
+ print('Path already exists. Rename it to [{:s}]'.format(new_name))
169
+ os.rename(path, new_name)
170
+ os.makedirs(path)
171
+
172
+
173
+ '''
174
+ # --------------------------------------------
175
+ # read image from path
176
+ # opencv is fast, but read BGR numpy image
177
+ # --------------------------------------------
178
+ '''
179
+
180
+
181
+ # --------------------------------------------
182
+ # get uint8 image of size HxWxn_channles (RGB)
183
+ # --------------------------------------------
184
+ def imread_uint(path, n_channels=3):
185
+ # input: path
186
+ # output: HxWx3(RGB or GGG), or HxWx1 (G)
187
+ if n_channels == 1:
188
+ img = cv2.imread(path, 0) # cv2.IMREAD_GRAYSCALE
189
+ img = np.expand_dims(img, axis=2) # HxWx1
190
+ elif n_channels == 3:
191
+ img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # BGR or G
192
+ if img.ndim == 2:
193
+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) # GGG
194
+ else:
195
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # RGB
196
+ return img
197
+
198
+
199
+ # --------------------------------------------
200
+ # matlab's imwrite
201
+ # --------------------------------------------
202
+ def imsave(img, img_path):
203
+ img = np.squeeze(img)
204
+ if img.ndim == 3:
205
+ img = img[:, :, [2, 1, 0]]
206
+ cv2.imwrite(img_path, img)
207
+
208
+ def imwrite(img, img_path):
209
+ img = np.squeeze(img)
210
+ if img.ndim == 3:
211
+ img = img[:, :, [2, 1, 0]]
212
+ cv2.imwrite(img_path, img)
213
+
214
+
215
+
216
+ # --------------------------------------------
217
+ # get single image of size HxWxn_channles (BGR)
218
+ # --------------------------------------------
219
+ def read_img(path):
220
+ # read image by cv2
221
+ # return: Numpy float32, HWC, BGR, [0,1]
222
+ img = cv2.imread(path, cv2.IMREAD_UNCHANGED) # cv2.IMREAD_GRAYSCALE
223
+ img = img.astype(np.float32) / 255.
224
+ if img.ndim == 2:
225
+ img = np.expand_dims(img, axis=2)
226
+ # some images have 4 channels
227
+ if img.shape[2] > 3:
228
+ img = img[:, :, :3]
229
+ return img
230
+
231
+
232
+ '''
233
+ # --------------------------------------------
234
+ # image format conversion
235
+ # --------------------------------------------
236
+ # numpy(single) <---> numpy(unit)
237
+ # numpy(single) <---> tensor
238
+ # numpy(unit) <---> tensor
239
+ # --------------------------------------------
240
+ '''
241
+
242
+
243
+ # --------------------------------------------
244
+ # numpy(single) [0, 1] <---> numpy(unit)
245
+ # --------------------------------------------
246
+
247
+
248
+ def uint2single(img):
249
+
250
+ return np.float32(img/255.)
251
+
252
+
253
+ def single2uint(img):
254
+
255
+ return np.uint8((img.clip(0, 1)*255.).round())
256
+
257
+
258
+ def uint162single(img):
259
+
260
+ return np.float32(img/65535.)
261
+
262
+
263
+ def single2uint16(img):
264
+
265
+ return np.uint16((img.clip(0, 1)*65535.).round())
266
+
267
+
268
+ # --------------------------------------------
269
+ # numpy(unit) (HxWxC or HxW) <---> tensor
270
+ # --------------------------------------------
271
+
272
+
273
+ # convert uint to 4-dimensional torch tensor
274
+ def uint2tensor4(img):
275
+ if img.ndim == 2:
276
+ img = np.expand_dims(img, axis=2)
277
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.).unsqueeze(0)
278
+
279
+
280
+ # convert uint to 3-dimensional torch tensor
281
+ def uint2tensor3(img):
282
+ if img.ndim == 2:
283
+ img = np.expand_dims(img, axis=2)
284
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().div(255.)
285
+
286
+
287
+ # convert 2/3/4-dimensional torch tensor to uint
288
+ def tensor2uint(img):
289
+ img = img.data.squeeze().float().clamp_(0, 1).cpu().numpy()
290
+ if img.ndim == 3:
291
+ img = np.transpose(img, (1, 2, 0))
292
+ return np.uint8((img*255.0).round())
293
+
294
+
295
+ # --------------------------------------------
296
+ # numpy(single) (HxWxC) <---> tensor
297
+ # --------------------------------------------
298
+
299
+
300
+ # convert single (HxWxC) to 3-dimensional torch tensor
301
+ def single2tensor3(img):
302
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float()
303
+
304
+
305
+ # convert single (HxWxC) to 4-dimensional torch tensor
306
+ def single2tensor4(img):
307
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1).float().unsqueeze(0)
308
+
309
+
310
+ # convert torch tensor to single
311
+ def tensor2single(img):
312
+ img = img.data.squeeze().float().cpu().numpy()
313
+ if img.ndim == 3:
314
+ img = np.transpose(img, (1, 2, 0))
315
+
316
+ return img
317
+
318
+ # convert torch tensor to single
319
+ def tensor2single3(img):
320
+ img = img.data.squeeze().float().cpu().numpy()
321
+ if img.ndim == 3:
322
+ img = np.transpose(img, (1, 2, 0))
323
+ elif img.ndim == 2:
324
+ img = np.expand_dims(img, axis=2)
325
+ return img
326
+
327
+
328
+ def single2tensor5(img):
329
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1, 3).float().unsqueeze(0)
330
+
331
+
332
+ def single32tensor5(img):
333
+ return torch.from_numpy(np.ascontiguousarray(img)).float().unsqueeze(0).unsqueeze(0)
334
+
335
+
336
+ def single42tensor4(img):
337
+ return torch.from_numpy(np.ascontiguousarray(img)).permute(2, 0, 1, 3).float()
338
+
339
+
340
+ # from skimage.io import imread, imsave
341
+ def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
342
+ '''
343
+ Converts a torch Tensor into an image Numpy array of BGR channel order
344
+ Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order
345
+ Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default)
346
+ '''
347
+ tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp
348
+ tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1]
349
+ n_dim = tensor.dim()
350
+ if n_dim == 4:
351
+ n_img = len(tensor)
352
+ img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy()
353
+ img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR
354
+ elif n_dim == 3:
355
+ img_np = tensor.numpy()
356
+ img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR
357
+ elif n_dim == 2:
358
+ img_np = tensor.numpy()
359
+ else:
360
+ raise TypeError(
361
+ 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim))
362
+ if out_type == np.uint8:
363
+ img_np = (img_np * 255.0).round()
364
+ # Important. Unlike matlab, numpy.unit8() WILL NOT round by default.
365
+ return img_np.astype(out_type)
366
+
367
+
368
+ '''
369
+ # --------------------------------------------
370
+ # Augmentation, flipe and/or rotate
371
+ # --------------------------------------------
372
+ # The following two are enough.
373
+ # (1) augmet_img: numpy image of WxHxC or WxH
374
+ # (2) augment_img_tensor4: tensor image 1xCxWxH
375
+ # --------------------------------------------
376
+ '''
377
+
378
+
379
+ def augment_img(img, mode=0):
380
+ '''Kai Zhang (github: https://github.com/cszn)
381
+ '''
382
+ if mode == 0:
383
+ return img
384
+ elif mode == 1:
385
+ return np.flipud(np.rot90(img))
386
+ elif mode == 2:
387
+ return np.flipud(img)
388
+ elif mode == 3:
389
+ return np.rot90(img, k=3)
390
+ elif mode == 4:
391
+ return np.flipud(np.rot90(img, k=2))
392
+ elif mode == 5:
393
+ return np.rot90(img)
394
+ elif mode == 6:
395
+ return np.rot90(img, k=2)
396
+ elif mode == 7:
397
+ return np.flipud(np.rot90(img, k=3))
398
+
399
+
400
+ def augment_img_tensor4(img, mode=0):
401
+ '''Kai Zhang (github: https://github.com/cszn)
402
+ '''
403
+ if mode == 0:
404
+ return img
405
+ elif mode == 1:
406
+ return img.rot90(1, [2, 3]).flip([2])
407
+ elif mode == 2:
408
+ return img.flip([2])
409
+ elif mode == 3:
410
+ return img.rot90(3, [2, 3])
411
+ elif mode == 4:
412
+ return img.rot90(2, [2, 3]).flip([2])
413
+ elif mode == 5:
414
+ return img.rot90(1, [2, 3])
415
+ elif mode == 6:
416
+ return img.rot90(2, [2, 3])
417
+ elif mode == 7:
418
+ return img.rot90(3, [2, 3]).flip([2])
419
+
420
+
421
+ def augment_img_tensor(img, mode=0):
422
+ '''Kai Zhang (github: https://github.com/cszn)
423
+ '''
424
+ img_size = img.size()
425
+ img_np = img.data.cpu().numpy()
426
+ if len(img_size) == 3:
427
+ img_np = np.transpose(img_np, (1, 2, 0))
428
+ elif len(img_size) == 4:
429
+ img_np = np.transpose(img_np, (2, 3, 1, 0))
430
+ img_np = augment_img(img_np, mode=mode)
431
+ img_tensor = torch.from_numpy(np.ascontiguousarray(img_np))
432
+ if len(img_size) == 3:
433
+ img_tensor = img_tensor.permute(2, 0, 1)
434
+ elif len(img_size) == 4:
435
+ img_tensor = img_tensor.permute(3, 2, 0, 1)
436
+
437
+ return img_tensor.type_as(img)
438
+
439
+
440
+ def augment_img_np3(img, mode=0):
441
+ if mode == 0:
442
+ return img
443
+ elif mode == 1:
444
+ return img.transpose(1, 0, 2)
445
+ elif mode == 2:
446
+ return img[::-1, :, :]
447
+ elif mode == 3:
448
+ img = img[::-1, :, :]
449
+ img = img.transpose(1, 0, 2)
450
+ return img
451
+ elif mode == 4:
452
+ return img[:, ::-1, :]
453
+ elif mode == 5:
454
+ img = img[:, ::-1, :]
455
+ img = img.transpose(1, 0, 2)
456
+ return img
457
+ elif mode == 6:
458
+ img = img[:, ::-1, :]
459
+ img = img[::-1, :, :]
460
+ return img
461
+ elif mode == 7:
462
+ img = img[:, ::-1, :]
463
+ img = img[::-1, :, :]
464
+ img = img.transpose(1, 0, 2)
465
+ return img
466
+
467
+
468
+ def augment_imgs(img_list, hflip=True, rot=True):
469
+ # horizontal flip OR rotate
470
+ hflip = hflip and random.random() < 0.5
471
+ vflip = rot and random.random() < 0.5
472
+ rot90 = rot and random.random() < 0.5
473
+
474
+ def _augment(img):
475
+ if hflip:
476
+ img = img[:, ::-1, :]
477
+ if vflip:
478
+ img = img[::-1, :, :]
479
+ if rot90:
480
+ img = img.transpose(1, 0, 2)
481
+ return img
482
+
483
+ return [_augment(img) for img in img_list]
484
+
485
+
486
+ '''
487
+ # --------------------------------------------
488
+ # modcrop and shave
489
+ # --------------------------------------------
490
+ '''
491
+
492
+
493
+ def modcrop(img_in, scale):
494
+ # img_in: Numpy, HWC or HW
495
+ img = np.copy(img_in)
496
+ if img.ndim == 2:
497
+ H, W = img.shape
498
+ H_r, W_r = H % scale, W % scale
499
+ img = img[:H - H_r, :W - W_r]
500
+ elif img.ndim == 3:
501
+ H, W, C = img.shape
502
+ H_r, W_r = H % scale, W % scale
503
+ img = img[:H - H_r, :W - W_r, :]
504
+ else:
505
+ raise ValueError('Wrong img ndim: [{:d}].'.format(img.ndim))
506
+ return img
507
+
508
+
509
+ def shave(img_in, border=0):
510
+ # img_in: Numpy, HWC or HW
511
+ img = np.copy(img_in)
512
+ h, w = img.shape[:2]
513
+ img = img[border:h-border, border:w-border]
514
+ return img
515
+
516
+
517
+ '''
518
+ # --------------------------------------------
519
+ # image processing process on numpy image
520
+ # channel_convert(in_c, tar_type, img_list):
521
+ # rgb2ycbcr(img, only_y=True):
522
+ # bgr2ycbcr(img, only_y=True):
523
+ # ycbcr2rgb(img):
524
+ # --------------------------------------------
525
+ '''
526
+
527
+
528
+ def rgb2ycbcr(img, only_y=True):
529
+ '''same as matlab rgb2ycbcr
530
+ only_y: only return Y channel
531
+ Input:
532
+ uint8, [0, 255]
533
+ float, [0, 1]
534
+ '''
535
+ in_img_type = img.dtype
536
+ img.astype(np.float32)
537
+ if in_img_type != np.uint8:
538
+ img *= 255.
539
+ # convert
540
+ if only_y:
541
+ rlt = np.dot(img, [65.481, 128.553, 24.966]) / 255.0 + 16.0
542
+ else:
543
+ rlt = np.matmul(img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],
544
+ [24.966, 112.0, -18.214]]) / 255.0 + [16, 128, 128]
545
+ if in_img_type == np.uint8:
546
+ rlt = rlt.round()
547
+ else:
548
+ rlt /= 255.
549
+ return rlt.astype(in_img_type)
550
+
551
+
552
+ def ycbcr2rgb(img):
553
+ '''same as matlab ycbcr2rgb
554
+ Input:
555
+ uint8, [0, 255]
556
+ float, [0, 1]
557
+ '''
558
+ in_img_type = img.dtype
559
+ img.astype(np.float32)
560
+ if in_img_type != np.uint8:
561
+ img *= 255.
562
+ # convert
563
+ rlt = np.matmul(img, [[0.00456621, 0.00456621, 0.00456621], [0, -0.00153632, 0.00791071],
564
+ [0.00625893, -0.00318811, 0]]) * 255.0 + [-222.921, 135.576, -276.836]
565
+ if in_img_type == np.uint8:
566
+ rlt = rlt.round()
567
+ else:
568
+ rlt /= 255.
569
+ return rlt.astype(in_img_type)
570
+
571
+
572
+ def bgr2ycbcr(img, only_y=True):
573
+ '''bgr version of rgb2ycbcr
574
+ only_y: only return Y channel
575
+ Input:
576
+ uint8, [0, 255]
577
+ float, [0, 1]
578
+ '''
579
+ in_img_type = img.dtype
580
+ img.astype(np.float32)
581
+ if in_img_type != np.uint8:
582
+ img *= 255.
583
+ # convert
584
+ if only_y:
585
+ rlt = np.dot(img, [24.966, 128.553, 65.481]) / 255.0 + 16.0
586
+ else:
587
+ rlt = np.matmul(img, [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786],
588
+ [65.481, -37.797, 112.0]]) / 255.0 + [16, 128, 128]
589
+ if in_img_type == np.uint8:
590
+ rlt = rlt.round()
591
+ else:
592
+ rlt /= 255.
593
+ return rlt.astype(in_img_type)
594
+
595
+
596
+ def channel_convert(in_c, tar_type, img_list):
597
+ # conversion among BGR, gray and y
598
+ if in_c == 3 and tar_type == 'gray': # BGR to gray
599
+ gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list]
600
+ return [np.expand_dims(img, axis=2) for img in gray_list]
601
+ elif in_c == 3 and tar_type == 'y': # BGR to y
602
+ y_list = [bgr2ycbcr(img, only_y=True) for img in img_list]
603
+ return [np.expand_dims(img, axis=2) for img in y_list]
604
+ elif in_c == 1 and tar_type == 'RGB': # gray/y to BGR
605
+ return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list]
606
+ else:
607
+ return img_list
608
+
609
+
610
+ '''
611
+ # --------------------------------------------
612
+ # metric, PSNR and SSIM
613
+ # --------------------------------------------
614
+ '''
615
+
616
+
617
+ # --------------------------------------------
618
+ # PSNR
619
+ # --------------------------------------------
620
+ def calculate_psnr(img1, img2, border=0):
621
+ # img1 and img2 have range [0, 255]
622
+ #img1 = img1.squeeze()
623
+ #img2 = img2.squeeze()
624
+ if not img1.shape == img2.shape:
625
+ raise ValueError('Input images must have the same dimensions.')
626
+ h, w = img1.shape[:2]
627
+ img1 = img1[border:h-border, border:w-border]
628
+ img2 = img2[border:h-border, border:w-border]
629
+
630
+ img1 = img1.astype(np.float64)
631
+ img2 = img2.astype(np.float64)
632
+ mse = np.mean((img1 - img2)**2)
633
+ if mse == 0:
634
+ return float('inf')
635
+ return 20 * math.log10(255.0 / math.sqrt(mse))
636
+
637
+
638
+ # --------------------------------------------
639
+ # BEF: Blocking effect factor
640
+ # --------------------------------------------
641
+ def compute_bef(img):
642
+
643
+ block = 8
644
+ height, width = img.shape[:2]
645
+
646
+ H = [i for i in range(width-1)]
647
+ H_B = [i for i in range(block-1,width-1,block)]
648
+ H_BC = list(set(H)-set(H_B))
649
+
650
+ V = [i for i in range(height-1)]
651
+ V_B = [i for i in range(block-1,height-1,block)]
652
+ V_BC = list(set(V)-set(V_B))
653
+
654
+ D_B = 0
655
+ D_BC = 0
656
+
657
+ for i in H_B:
658
+ diff = img[:,i] - img[:,i+1]
659
+ D_B += np.sum(diff**2)
660
+
661
+ for i in H_BC:
662
+ diff = img[:,i] - img[:,i+1]
663
+ D_BC += np.sum(diff**2)
664
+
665
+
666
+ for j in V_B:
667
+ diff = img[j,:] - img[j+1,:]
668
+ D_B += np.sum(diff**2)
669
+
670
+ for j in V_BC:
671
+ diff = img[j,:] - img[j+1,:]
672
+ D_BC += np.sum(diff**2)
673
+
674
+
675
+ N_HB = height * (width/block - 1)
676
+ N_HBC = height * (width - 1) - N_HB
677
+ N_VB = width * (height/block -1)
678
+ N_VBC = width * (height -1) - N_VB
679
+ D_B = D_B / (N_HB + N_VB)
680
+ D_BC = D_BC / (N_HBC + N_VBC)
681
+ eta = math.log2(block) / math.log2(min(height, width)) if D_B > D_BC else 0
682
+ return eta * (D_B - D_BC)
683
+
684
+
685
+
686
+ # --------------------------------------------
687
+ # PSNRB
688
+ # --------------------------------------------
689
+ def calculate_psnrb(img1, img2, border=0):
690
+ # img1: ground truth
691
+ # img2: compressed image
692
+ # img1 and img2 have range [0, 255]
693
+ #img1 = img1.squeeze()
694
+ #img2 = img2.squeeze()
695
+ if not img1.shape == img2.shape:
696
+ raise ValueError('Input images must have the same dimensions.')
697
+ h, w = img1.shape[:2]
698
+ img1 = img1[border:h-border, border:w-border]
699
+ img2 = img2[border:h-border, border:w-border]
700
+ img1 = img1.astype(np.float64)
701
+ if img2.shape[-1]==3:
702
+ img2_y = rgb2ycbcr(img2).astype(np.float64)
703
+ bef = compute_bef(img2_y)
704
+ else:
705
+ img2 = img2.astype(np.float64)
706
+ bef = compute_bef(img2)
707
+ mse = np.mean((img1 - img2)**2)
708
+ mse_b = mse + bef
709
+ if mse_b == 0:
710
+ return float('inf')
711
+ return 20 * math.log10(255.0 / math.sqrt(mse_b))
712
+
713
+
714
+
715
+ # --------------------------------------------
716
+ # SSIM
717
+ # --------------------------------------------
718
+ def calculate_ssim(img1, img2, border=0):
719
+ '''calculate SSIM
720
+ the same outputs as MATLAB's
721
+ img1, img2: [0, 255]
722
+ '''
723
+ #img1 = img1.squeeze()
724
+ #img2 = img2.squeeze()
725
+ if not img1.shape == img2.shape:
726
+ raise ValueError('Input images must have the same dimensions.')
727
+ h, w = img1.shape[:2]
728
+ img1 = img1[border:h-border, border:w-border]
729
+ img2 = img2[border:h-border, border:w-border]
730
+
731
+ if img1.ndim == 2:
732
+ return ssim(img1, img2)
733
+ elif img1.ndim == 3:
734
+ if img1.shape[2] == 3:
735
+ ssims = []
736
+ for i in range(3):
737
+ ssims.append(ssim(img1[:,:,i], img2[:,:,i]))
738
+ return np.array(ssims).mean()
739
+ elif img1.shape[2] == 1:
740
+ return ssim(np.squeeze(img1), np.squeeze(img2))
741
+ else:
742
+ raise ValueError('Wrong input image dimensions.')
743
+
744
+
745
+ def ssim(img1, img2):
746
+ C1 = (0.01 * 255)**2
747
+ C2 = (0.03 * 255)**2
748
+
749
+ img1 = img1.astype(np.float64)
750
+ img2 = img2.astype(np.float64)
751
+ kernel = cv2.getGaussianKernel(11, 1.5)
752
+ window = np.outer(kernel, kernel.transpose())
753
+
754
+ mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid
755
+ mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
756
+ mu1_sq = mu1**2
757
+ mu2_sq = mu2**2
758
+ mu1_mu2 = mu1 * mu2
759
+ sigma1_sq = cv2.filter2D(img1**2, -1, window)[5:-5, 5:-5] - mu1_sq
760
+ sigma2_sq = cv2.filter2D(img2**2, -1, window)[5:-5, 5:-5] - mu2_sq
761
+ sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
762
+
763
+ ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *
764
+ (sigma1_sq + sigma2_sq + C2))
765
+ return ssim_map.mean()
766
+
767
+
768
+ '''
769
+ # --------------------------------------------
770
+ # matlab's bicubic imresize (numpy and torch) [0, 1]
771
+ # --------------------------------------------
772
+ '''
773
+
774
+
775
+ # matlab 'imresize' function, now only support 'bicubic'
776
+ def cubic(x):
777
+ absx = torch.abs(x)
778
+ absx2 = absx**2
779
+ absx3 = absx**3
780
+ return (1.5*absx3 - 2.5*absx2 + 1) * ((absx <= 1).type_as(absx)) + \
781
+ (-0.5*absx3 + 2.5*absx2 - 4*absx + 2) * (((absx > 1)*(absx <= 2)).type_as(absx))
782
+
783
+
784
+ def calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing):
785
+ if (scale < 1) and (antialiasing):
786
+ # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width
787
+ kernel_width = kernel_width / scale
788
+
789
+ # Output-space coordinates
790
+ x = torch.linspace(1, out_length, out_length)
791
+
792
+ # Input-space coordinates. Calculate the inverse mapping such that 0.5
793
+ # in output space maps to 0.5 in input space, and 0.5+scale in output
794
+ # space maps to 1.5 in input space.
795
+ u = x / scale + 0.5 * (1 - 1 / scale)
796
+
797
+ # What is the left-most pixel that can be involved in the computation?
798
+ left = torch.floor(u - kernel_width / 2)
799
+
800
+ # What is the maximum number of pixels that can be involved in the
801
+ # computation? Note: it's OK to use an extra pixel here; if the
802
+ # corresponding weights are all zero, it will be eliminated at the end
803
+ # of this function.
804
+ P = math.ceil(kernel_width) + 2
805
+
806
+ # The indices of the input pixels involved in computing the k-th output
807
+ # pixel are in row k of the indices matrix.
808
+ indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace(0, P - 1, P).view(
809
+ 1, P).expand(out_length, P)
810
+
811
+ # The weights used to compute the k-th output pixel are in row k of the
812
+ # weights matrix.
813
+ distance_to_center = u.view(out_length, 1).expand(out_length, P) - indices
814
+ # apply cubic kernel
815
+ if (scale < 1) and (antialiasing):
816
+ weights = scale * cubic(distance_to_center * scale)
817
+ else:
818
+ weights = cubic(distance_to_center)
819
+ # Normalize the weights matrix so that each row sums to 1.
820
+ weights_sum = torch.sum(weights, 1).view(out_length, 1)
821
+ weights = weights / weights_sum.expand(out_length, P)
822
+
823
+ # If a column in weights is all zero, get rid of it. only consider the first and last column.
824
+ weights_zero_tmp = torch.sum((weights == 0), 0)
825
+ if not math.isclose(weights_zero_tmp[0], 0, rel_tol=1e-6):
826
+ indices = indices.narrow(1, 1, P - 2)
827
+ weights = weights.narrow(1, 1, P - 2)
828
+ if not math.isclose(weights_zero_tmp[-1], 0, rel_tol=1e-6):
829
+ indices = indices.narrow(1, 0, P - 2)
830
+ weights = weights.narrow(1, 0, P - 2)
831
+ weights = weights.contiguous()
832
+ indices = indices.contiguous()
833
+ sym_len_s = -indices.min() + 1
834
+ sym_len_e = indices.max() - in_length
835
+ indices = indices + sym_len_s - 1
836
+ return weights, indices, int(sym_len_s), int(sym_len_e)
837
+
838
+
839
+ # --------------------------------------------
840
+ # imresize for tensor image [0, 1]
841
+ # --------------------------------------------
842
+ def imresize(img, scale, antialiasing=True):
843
+ # Now the scale should be the same for H and W
844
+ # input: img: pytorch tensor, CHW or HW [0,1]
845
+ # output: CHW or HW [0,1] w/o round
846
+ need_squeeze = True if img.dim() == 2 else False
847
+ if need_squeeze:
848
+ img.unsqueeze_(0)
849
+ in_C, in_H, in_W = img.size()
850
+ out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale)
851
+ kernel_width = 4
852
+ kernel = 'cubic'
853
+
854
+ # Return the desired dimension order for performing the resize. The
855
+ # strategy is to perform the resize first along the dimension with the
856
+ # smallest scale factor.
857
+ # Now we do not support this.
858
+
859
+ # get weights and indices
860
+ weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices(
861
+ in_H, out_H, scale, kernel, kernel_width, antialiasing)
862
+ weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices(
863
+ in_W, out_W, scale, kernel, kernel_width, antialiasing)
864
+ # process H dimension
865
+ # symmetric copying
866
+ img_aug = torch.FloatTensor(in_C, in_H + sym_len_Hs + sym_len_He, in_W)
867
+ img_aug.narrow(1, sym_len_Hs, in_H).copy_(img)
868
+
869
+ sym_patch = img[:, :sym_len_Hs, :]
870
+ inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()
871
+ sym_patch_inv = sym_patch.index_select(1, inv_idx)
872
+ img_aug.narrow(1, 0, sym_len_Hs).copy_(sym_patch_inv)
873
+
874
+ sym_patch = img[:, -sym_len_He:, :]
875
+ inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()
876
+ sym_patch_inv = sym_patch.index_select(1, inv_idx)
877
+ img_aug.narrow(1, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv)
878
+
879
+ out_1 = torch.FloatTensor(in_C, out_H, in_W)
880
+ kernel_width = weights_H.size(1)
881
+ for i in range(out_H):
882
+ idx = int(indices_H[i][0])
883
+ for j in range(out_C):
884
+ out_1[j, i, :] = img_aug[j, idx:idx + kernel_width, :].transpose(0, 1).mv(weights_H[i])
885
+
886
+ # process W dimension
887
+ # symmetric copying
888
+ out_1_aug = torch.FloatTensor(in_C, out_H, in_W + sym_len_Ws + sym_len_We)
889
+ out_1_aug.narrow(2, sym_len_Ws, in_W).copy_(out_1)
890
+
891
+ sym_patch = out_1[:, :, :sym_len_Ws]
892
+ inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long()
893
+ sym_patch_inv = sym_patch.index_select(2, inv_idx)
894
+ out_1_aug.narrow(2, 0, sym_len_Ws).copy_(sym_patch_inv)
895
+
896
+ sym_patch = out_1[:, :, -sym_len_We:]
897
+ inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long()
898
+ sym_patch_inv = sym_patch.index_select(2, inv_idx)
899
+ out_1_aug.narrow(2, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv)
900
+
901
+ out_2 = torch.FloatTensor(in_C, out_H, out_W)
902
+ kernel_width = weights_W.size(1)
903
+ for i in range(out_W):
904
+ idx = int(indices_W[i][0])
905
+ for j in range(out_C):
906
+ out_2[j, :, i] = out_1_aug[j, :, idx:idx + kernel_width].mv(weights_W[i])
907
+ if need_squeeze:
908
+ out_2.squeeze_()
909
+ return out_2
910
+
911
+
912
+ # --------------------------------------------
913
+ # imresize for numpy image [0, 1]
914
+ # --------------------------------------------
915
+ def imresize_np(img, scale, antialiasing=True):
916
+ # Now the scale should be the same for H and W
917
+ # input: img: Numpy, HWC or HW [0,1]
918
+ # output: HWC or HW [0,1] w/o round
919
+ img = torch.from_numpy(img)
920
+ need_squeeze = True if img.dim() == 2 else False
921
+ if need_squeeze:
922
+ img.unsqueeze_(2)
923
+
924
+ in_H, in_W, in_C = img.size()
925
+ out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale)
926
+ kernel_width = 4
927
+ kernel = 'cubic'
928
+
929
+ # Return the desired dimension order for performing the resize. The
930
+ # strategy is to perform the resize first along the dimension with the
931
+ # smallest scale factor.
932
+ # Now we do not support this.
933
+
934
+ # get weights and indices
935
+ weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices(
936
+ in_H, out_H, scale, kernel, kernel_width, antialiasing)
937
+ weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices(
938
+ in_W, out_W, scale, kernel, kernel_width, antialiasing)
939
+ # process H dimension
940
+ # symmetric copying
941
+ img_aug = torch.FloatTensor(in_H + sym_len_Hs + sym_len_He, in_W, in_C)
942
+ img_aug.narrow(0, sym_len_Hs, in_H).copy_(img)
943
+
944
+ sym_patch = img[:sym_len_Hs, :, :]
945
+ inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long()
946
+ sym_patch_inv = sym_patch.index_select(0, inv_idx)
947
+ img_aug.narrow(0, 0, sym_len_Hs).copy_(sym_patch_inv)
948
+
949
+ sym_patch = img[-sym_len_He:, :, :]
950
+ inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long()
951
+ sym_patch_inv = sym_patch.index_select(0, inv_idx)
952
+ img_aug.narrow(0, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv)
953
+
954
+ out_1 = torch.FloatTensor(out_H, in_W, in_C)
955
+ kernel_width = weights_H.size(1)
956
+ for i in range(out_H):
957
+ idx = int(indices_H[i][0])
958
+ for j in range(out_C):
959
+ out_1[i, :, j] = img_aug[idx:idx + kernel_width, :, j].transpose(0, 1).mv(weights_H[i])
960
+
961
+ # process W dimension
962
+ # symmetric copying
963
+ out_1_aug = torch.FloatTensor(out_H, in_W + sym_len_Ws + sym_len_We, in_C)
964
+ out_1_aug.narrow(1, sym_len_Ws, in_W).copy_(out_1)
965
+
966
+ sym_patch = out_1[:, :sym_len_Ws, :]
967
+ inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()
968
+ sym_patch_inv = sym_patch.index_select(1, inv_idx)
969
+ out_1_aug.narrow(1, 0, sym_len_Ws).copy_(sym_patch_inv)
970
+
971
+ sym_patch = out_1[:, -sym_len_We:, :]
972
+ inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()
973
+ sym_patch_inv = sym_patch.index_select(1, inv_idx)
974
+ out_1_aug.narrow(1, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv)
975
+
976
+ out_2 = torch.FloatTensor(out_H, out_W, in_C)
977
+ kernel_width = weights_W.size(1)
978
+ for i in range(out_W):
979
+ idx = int(indices_W[i][0])
980
+ for j in range(out_C):
981
+ out_2[:, i, j] = out_1_aug[:, idx:idx + kernel_width, j].mv(weights_W[i])
982
+ if need_squeeze:
983
+ out_2.squeeze_()
984
+
985
+ return out_2.numpy()
986
+
987
+
988
+ if __name__ == '__main__':
989
+ img = imread_uint('test.bmp', 3)
990
+ # img = uint2single(img)
991
+ # img_bicubic = imresize_np(img, 1/4)
992
+ # imshow(single2uint(img_bicubic))
993
+ #
994
+ # img_tensor = single2tensor4(img)
995
+ # for i in range(8):
996
+ # imshow(np.concatenate((augment_img(img, i), tensor2single(augment_img_tensor4(img_tensor, i))), 1))
997
+
998
+ # patches = patches_from_image(img, p_size=128, p_overlap=0, p_max=200)
999
+ # imssave(patches,'a.png')