Spaces:
Runtime error
Runtime error
Ajay Harikumar
commited on
Commit
•
feff774
1
Parent(s):
8ee7972
Add initial versions of files without resolution constrain
Browse files- app.py +181 -0
- network_fbcnn.py +337 -0
- packages.txt +1 -0
- requirements.txt +3 -0
- utils_image.py +999 -0
app.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os.path
|
3 |
+
import numpy as np
|
4 |
+
from collections import OrderedDict
|
5 |
+
import torch
|
6 |
+
import cv2
|
7 |
+
from PIL import Image, ImageOps
|
8 |
+
import utils_image as util
|
9 |
+
from network_fbcnn import FBCNN as net
|
10 |
+
import requests
|
11 |
+
import datetime
|
12 |
+
|
13 |
+
for model_path in ['fbcnn_gray.pth','fbcnn_color.pth']:
|
14 |
+
if os.path.exists(model_path):
|
15 |
+
print(f'{model_path} exists.')
|
16 |
+
else:
|
17 |
+
print("downloading model")
|
18 |
+
url = 'https://github.com/jiaxi-jiang/FBCNN/releases/download/v1.0/{}'.format(os.path.basename(model_path))
|
19 |
+
r = requests.get(url, allow_redirects=True)
|
20 |
+
open(model_path, 'wb').write(r.content)
|
21 |
+
|
22 |
+
def inference(input_img, is_gray, input_quality, zoom, x_shift, y_shift):
|
23 |
+
|
24 |
+
print("datetime:",datetime.datetime.utcnow())
|
25 |
+
input_img_width, input_img_height = Image.fromarray(input_img).size
|
26 |
+
print("img size:",(input_img_width,input_img_height))
|
27 |
+
|
28 |
+
if (input_img_width > 1080) or (input_img_height > 1080):
|
29 |
+
resize_ratio = min(1080/input_img_width, 1080/input_img_height)
|
30 |
+
resized_input = Image.fromarray(input_img).resize((int(input_img_width*resize_ratio)+(input_img_width*resize_ratio < 1),
|
31 |
+
int(input_img_height*resize_ratio)+(input_img_height*resize_ratio < 1)),
|
32 |
+
resample=Image.BICUBIC)
|
33 |
+
input_img = np.array(resized_input)
|
34 |
+
print("input image resized to:", resized_input.size)
|
35 |
+
|
36 |
+
if is_gray:
|
37 |
+
n_channels = 1 # set 1 for grayscale image, set 3 for color image
|
38 |
+
model_name = 'fbcnn_gray.pth'
|
39 |
+
else:
|
40 |
+
n_channels = 3 # set 1 for grayscale image, set 3 for color image
|
41 |
+
model_name = 'fbcnn_color.pth'
|
42 |
+
nc = [64,128,256,512]
|
43 |
+
nb = 4
|
44 |
+
|
45 |
+
|
46 |
+
input_quality = 100 - input_quality
|
47 |
+
|
48 |
+
model_path = model_name
|
49 |
+
|
50 |
+
if os.path.exists(model_path):
|
51 |
+
print(f'{model_path} already exists.')
|
52 |
+
else:
|
53 |
+
print("downloading model")
|
54 |
+
os.makedirs(os.path.dirname(model_path), exist_ok=True)
|
55 |
+
url = 'https://github.com/jiaxi-jiang/FBCNN/releases/download/v1.0/{}'.format(os.path.basename(model_path))
|
56 |
+
r = requests.get(url, allow_redirects=True)
|
57 |
+
open(model_path, 'wb').write(r.content)
|
58 |
+
|
59 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
60 |
+
print("device:",device)
|
61 |
+
|
62 |
+
# ----------------------------------------
|
63 |
+
# load model
|
64 |
+
# ----------------------------------------
|
65 |
+
|
66 |
+
print(f'loading model from {model_path}')
|
67 |
+
|
68 |
+
model = net(in_nc=n_channels, out_nc=n_channels, nc=nc, nb=nb, act_mode='R')
|
69 |
+
print("#model.load_state_dict(torch.load(model_path), strict=True)")
|
70 |
+
model.load_state_dict(torch.load(model_path), strict=True)
|
71 |
+
print("#model.eval()")
|
72 |
+
model.eval()
|
73 |
+
print("#for k, v in model.named_parameters()")
|
74 |
+
for k, v in model.named_parameters():
|
75 |
+
v.requires_grad = False
|
76 |
+
print("#model.to(device)")
|
77 |
+
model = model.to(device)
|
78 |
+
print("Model loaded.")
|
79 |
+
|
80 |
+
test_results = OrderedDict()
|
81 |
+
test_results['psnr'] = []
|
82 |
+
test_results['ssim'] = []
|
83 |
+
test_results['psnrb'] = []
|
84 |
+
|
85 |
+
# ------------------------------------
|
86 |
+
# (1) img_L
|
87 |
+
# ------------------------------------
|
88 |
+
|
89 |
+
print("#if n_channels")
|
90 |
+
if n_channels == 1:
|
91 |
+
open_cv_image = Image.fromarray(input_img)
|
92 |
+
open_cv_image = ImageOps.grayscale(open_cv_image)
|
93 |
+
open_cv_image = np.array(open_cv_image) # PIL to open cv image
|
94 |
+
img = np.expand_dims(open_cv_image, axis=2) # HxWx1
|
95 |
+
elif n_channels == 3:
|
96 |
+
open_cv_image = np.array(input_img) # PIL to open cv image
|
97 |
+
if open_cv_image.ndim == 2:
|
98 |
+
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_GRAY2RGB) # GGG
|
99 |
+
else:
|
100 |
+
open_cv_image = cv2.cvtColor(open_cv_image, cv2.COLOR_BGR2RGB) # RGB
|
101 |
+
|
102 |
+
print("#util.uint2tensor4(open_cv_image)")
|
103 |
+
img_L = util.uint2tensor4(open_cv_image)
|
104 |
+
|
105 |
+
print("#img_L.to(device)")
|
106 |
+
img_L = img_L.to(device)
|
107 |
+
|
108 |
+
# ------------------------------------
|
109 |
+
# (2) img_E
|
110 |
+
# ------------------------------------
|
111 |
+
|
112 |
+
print("#model(img_L)")
|
113 |
+
img_E,QF = model(img_L)
|
114 |
+
print("#util.tensor2single(img_E)")
|
115 |
+
img_E = util.tensor2single(img_E)
|
116 |
+
print("#util.single2uint(img_E)")
|
117 |
+
img_E = util.single2uint(img_E)
|
118 |
+
|
119 |
+
print("#torch.tensor([[1-input_quality/100]]).cuda() || torch.tensor([[1-input_quality/100]])")
|
120 |
+
qf_input = torch.tensor([[1-input_quality/100]]).cuda() if device == torch.device('cuda') else torch.tensor([[1-input_quality/100]])
|
121 |
+
print("#util.single2uint(img_E)")
|
122 |
+
img_E,QF = model(img_L, qf_input)
|
123 |
+
|
124 |
+
print("#util.tensor2single(img_E)")
|
125 |
+
img_E = util.tensor2single(img_E)
|
126 |
+
print("#util.single2uint(img_E)")
|
127 |
+
img_E = util.single2uint(img_E)
|
128 |
+
|
129 |
+
if img_E.ndim == 3:
|
130 |
+
img_E = img_E[:, :, [2, 1, 0]]
|
131 |
+
|
132 |
+
print("--inference finished")
|
133 |
+
|
134 |
+
out_img = Image.fromarray(img_E)
|
135 |
+
out_img_w, out_img_h = out_img.size # output image size
|
136 |
+
zoom = zoom/100
|
137 |
+
x_shift = x_shift/100
|
138 |
+
y_shift = y_shift/100
|
139 |
+
zoom_w, zoom_h = out_img_w*zoom, out_img_h*zoom
|
140 |
+
zoom_left, zoom_right = int((out_img_w - zoom_w)*x_shift), int(zoom_w + (out_img_w - zoom_w)*x_shift)
|
141 |
+
zoom_top, zoom_bottom = int((out_img_h - zoom_h)*y_shift), int(zoom_h + (out_img_h - zoom_h)*y_shift)
|
142 |
+
in_img = Image.fromarray(input_img)
|
143 |
+
in_img = in_img.crop((zoom_left, zoom_top, zoom_right, zoom_bottom))
|
144 |
+
in_img = in_img.resize((int(zoom_w/zoom), int(zoom_h/zoom)), Image.NEAREST)
|
145 |
+
out_img = out_img.crop((zoom_left, zoom_top, zoom_right, zoom_bottom))
|
146 |
+
out_img = out_img.resize((int(zoom_w/zoom), int(zoom_h/zoom)), Image.NEAREST)
|
147 |
+
|
148 |
+
print("--generating preview finished")
|
149 |
+
|
150 |
+
return img_E, in_img, out_img
|
151 |
+
|
152 |
+
gr.Interface(
|
153 |
+
fn = inference,
|
154 |
+
inputs = [gr.inputs.Image(label="Input Image"),
|
155 |
+
gr.inputs.Checkbox(label="Grayscale (Check this if your image is grayscale)"),
|
156 |
+
gr.inputs.Slider(minimum=1, maximum=100, step=1, label="Intensity (Higher = stronger JPEG artifact removal)"),
|
157 |
+
gr.inputs.Slider(minimum=10, maximum=100, step=1, default=50, label="Zoom Image "
|
158 |
+
"(Use this to see a copy of the output image up close. "
|
159 |
+
"100 = original size)"),
|
160 |
+
gr.inputs.Slider(minimum=0, maximum=100, step=1, label="Zoom horizontal shift "
|
161 |
+
"(Increase to shift to the right)"),
|
162 |
+
gr.inputs.Slider(minimum=0, maximum=100, step=1, label="Zoom vertical shift "
|
163 |
+
"(Increase to shift downwards)")
|
164 |
+
],
|
165 |
+
outputs = [gr.outputs.Image(label="Result"),
|
166 |
+
gr.outputs.Image(label="Before:"),
|
167 |
+
gr.outputs.Image(label="After:")],
|
168 |
+
title = "JPEG Artifacts Removal [FBCNN]",
|
169 |
+
description = "Gradio Demo for JPEG Artifacts Removal. To use it, simply upload your image, "
|
170 |
+
"Check out the paper and the original GitHub repo at the links below. "
|
171 |
+
"JPEG artifacts are noticeable distortions of images caused by JPEG lossy compression. "
|
172 |
+
"This is not a super-resolution AI but a JPEG compression artifact remover. "
|
173 |
+
"Written below are the limitations of the input image. ",
|
174 |
+
article = "<p style='text-align: left;'>Uploaded images with transparency will be incorrectly reconstructed at the output.</p>"
|
175 |
+
"<p style='text-align: center;'><a href='https://github.com/jiaxi-jiang/FBCNN'>FBCNN GitHub Repo</a><br>"
|
176 |
+
"<a href='https://arxiv.org/abs/2109.14573'>Towards Flexible Blind JPEG Artifacts Removal (FBCNN, ICCV 2021)</a><br>"
|
177 |
+
"<a href='https://jiaxi-jiang.github.io/'>Jiaxi Jiang, </a>"
|
178 |
+
"<a href='https://cszn.github.io/'>Kai Zhang, </a>"
|
179 |
+
"<a href='http://people.ee.ethz.ch/~timofter/'>Radu Timofte</a></p>",
|
180 |
+
allow_flagging="never"
|
181 |
+
).launch(enable_queue=True)
|
network_fbcnn.py
ADDED
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import OrderedDict
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import numpy as np
|
5 |
+
import torch.nn.functional as F
|
6 |
+
import torchvision.models as models
|
7 |
+
|
8 |
+
'''
|
9 |
+
# --------------------------------------------
|
10 |
+
# Advanced nn.Sequential
|
11 |
+
# https://github.com/xinntao/BasicSR
|
12 |
+
# --------------------------------------------
|
13 |
+
'''
|
14 |
+
|
15 |
+
|
16 |
+
def sequential(*args):
|
17 |
+
"""Advanced nn.Sequential.
|
18 |
+
|
19 |
+
Args:
|
20 |
+
nn.Sequential, nn.Module
|
21 |
+
|
22 |
+
Returns:
|
23 |
+
nn.Sequential
|
24 |
+
"""
|
25 |
+
if len(args) == 1:
|
26 |
+
if isinstance(args[0], OrderedDict):
|
27 |
+
raise NotImplementedError('sequential does not support OrderedDict input.')
|
28 |
+
return args[0] # No sequential is needed.
|
29 |
+
modules = []
|
30 |
+
for module in args:
|
31 |
+
if isinstance(module, nn.Sequential):
|
32 |
+
for submodule in module.children():
|
33 |
+
modules.append(submodule)
|
34 |
+
elif isinstance(module, nn.Module):
|
35 |
+
modules.append(module)
|
36 |
+
return nn.Sequential(*modules)
|
37 |
+
|
38 |
+
# --------------------------------------------
|
39 |
+
# return nn.Sequantial of (Conv + BN + ReLU)
|
40 |
+
# --------------------------------------------
|
41 |
+
def conv(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CBR', negative_slope=0.2):
|
42 |
+
L = []
|
43 |
+
for t in mode:
|
44 |
+
if t == 'C':
|
45 |
+
L.append(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
|
46 |
+
elif t == 'T':
|
47 |
+
L.append(nn.ConvTranspose2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
|
48 |
+
elif t == 'B':
|
49 |
+
L.append(nn.BatchNorm2d(out_channels, momentum=0.9, eps=1e-04, affine=True))
|
50 |
+
elif t == 'I':
|
51 |
+
L.append(nn.InstanceNorm2d(out_channels, affine=True))
|
52 |
+
elif t == 'R':
|
53 |
+
L.append(nn.ReLU(inplace=True))
|
54 |
+
elif t == 'r':
|
55 |
+
L.append(nn.ReLU(inplace=False))
|
56 |
+
elif t == 'L':
|
57 |
+
L.append(nn.LeakyReLU(negative_slope=negative_slope, inplace=True))
|
58 |
+
elif t == 'l':
|
59 |
+
L.append(nn.LeakyReLU(negative_slope=negative_slope, inplace=False))
|
60 |
+
elif t == '2':
|
61 |
+
L.append(nn.PixelShuffle(upscale_factor=2))
|
62 |
+
elif t == '3':
|
63 |
+
L.append(nn.PixelShuffle(upscale_factor=3))
|
64 |
+
elif t == '4':
|
65 |
+
L.append(nn.PixelShuffle(upscale_factor=4))
|
66 |
+
elif t == 'U':
|
67 |
+
L.append(nn.Upsample(scale_factor=2, mode='nearest'))
|
68 |
+
elif t == 'u':
|
69 |
+
L.append(nn.Upsample(scale_factor=3, mode='nearest'))
|
70 |
+
elif t == 'v':
|
71 |
+
L.append(nn.Upsample(scale_factor=4, mode='nearest'))
|
72 |
+
elif t == 'M':
|
73 |
+
L.append(nn.MaxPool2d(kernel_size=kernel_size, stride=stride, padding=0))
|
74 |
+
elif t == 'A':
|
75 |
+
L.append(nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=0))
|
76 |
+
else:
|
77 |
+
raise NotImplementedError('Undefined type: '.format(t))
|
78 |
+
return sequential(*L)
|
79 |
+
|
80 |
+
# --------------------------------------------
|
81 |
+
# Res Block: x + conv(relu(conv(x)))
|
82 |
+
# --------------------------------------------
|
83 |
+
class ResBlock(nn.Module):
|
84 |
+
def __init__(self, in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CRC', negative_slope=0.2):
|
85 |
+
super(ResBlock, self).__init__()
|
86 |
+
|
87 |
+
assert in_channels == out_channels, 'Only support in_channels==out_channels.'
|
88 |
+
if mode[0] in ['R', 'L']:
|
89 |
+
mode = mode[0].lower() + mode[1:]
|
90 |
+
|
91 |
+
self.res = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
|
92 |
+
|
93 |
+
def forward(self, x):
|
94 |
+
res = self.res(x)
|
95 |
+
return x + res
|
96 |
+
|
97 |
+
# --------------------------------------------
|
98 |
+
# conv + subp (+ relu)
|
99 |
+
# --------------------------------------------
|
100 |
+
def upsample_pixelshuffle(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
|
101 |
+
assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
|
102 |
+
up1 = conv(in_channels, out_channels * (int(mode[0]) ** 2), kernel_size, stride, padding, bias, mode='C'+mode, negative_slope=negative_slope)
|
103 |
+
return up1
|
104 |
+
|
105 |
+
|
106 |
+
# --------------------------------------------
|
107 |
+
# nearest_upsample + conv (+ R)
|
108 |
+
# --------------------------------------------
|
109 |
+
def upsample_upconv(in_channels=64, out_channels=3, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
|
110 |
+
assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR'
|
111 |
+
if mode[0] == '2':
|
112 |
+
uc = 'UC'
|
113 |
+
elif mode[0] == '3':
|
114 |
+
uc = 'uC'
|
115 |
+
elif mode[0] == '4':
|
116 |
+
uc = 'vC'
|
117 |
+
mode = mode.replace(mode[0], uc)
|
118 |
+
up1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode, negative_slope=negative_slope)
|
119 |
+
return up1
|
120 |
+
|
121 |
+
|
122 |
+
# --------------------------------------------
|
123 |
+
# convTranspose (+ relu)
|
124 |
+
# --------------------------------------------
|
125 |
+
def upsample_convtranspose(in_channels=64, out_channels=3, kernel_size=2, stride=2, padding=0, bias=True, mode='2R', negative_slope=0.2):
|
126 |
+
assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
|
127 |
+
kernel_size = int(mode[0])
|
128 |
+
stride = int(mode[0])
|
129 |
+
mode = mode.replace(mode[0], 'T')
|
130 |
+
up1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
|
131 |
+
return up1
|
132 |
+
|
133 |
+
|
134 |
+
'''
|
135 |
+
# --------------------------------------------
|
136 |
+
# Downsampler
|
137 |
+
# Kai Zhang, https://github.com/cszn/KAIR
|
138 |
+
# --------------------------------------------
|
139 |
+
# downsample_strideconv
|
140 |
+
# downsample_maxpool
|
141 |
+
# downsample_avgpool
|
142 |
+
# --------------------------------------------
|
143 |
+
'''
|
144 |
+
|
145 |
+
|
146 |
+
# --------------------------------------------
|
147 |
+
# strideconv (+ relu)
|
148 |
+
# --------------------------------------------
|
149 |
+
def downsample_strideconv(in_channels=64, out_channels=64, kernel_size=2, stride=2, padding=0, bias=True, mode='2R', negative_slope=0.2):
|
150 |
+
assert len(mode)<4 and mode[0] in ['2', '3', '4'], 'mode examples: 2, 2R, 2BR, 3, ..., 4BR.'
|
151 |
+
kernel_size = int(mode[0])
|
152 |
+
stride = int(mode[0])
|
153 |
+
mode = mode.replace(mode[0], 'C')
|
154 |
+
down1 = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
|
155 |
+
return down1
|
156 |
+
|
157 |
+
|
158 |
+
# --------------------------------------------
|
159 |
+
# maxpooling + conv (+ relu)
|
160 |
+
# --------------------------------------------
|
161 |
+
def downsample_maxpool(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=0, bias=True, mode='2R', negative_slope=0.2):
|
162 |
+
assert len(mode)<4 and mode[0] in ['2', '3'], 'mode examples: 2, 2R, 2BR, 3, ..., 3BR.'
|
163 |
+
kernel_size_pool = int(mode[0])
|
164 |
+
stride_pool = int(mode[0])
|
165 |
+
mode = mode.replace(mode[0], 'MC')
|
166 |
+
pool = conv(kernel_size=kernel_size_pool, stride=stride_pool, mode=mode[0], negative_slope=negative_slope)
|
167 |
+
pool_tail = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode[1:], negative_slope=negative_slope)
|
168 |
+
return sequential(pool, pool_tail)
|
169 |
+
|
170 |
+
|
171 |
+
# --------------------------------------------
|
172 |
+
# averagepooling + conv (+ relu)
|
173 |
+
# --------------------------------------------
|
174 |
+
def downsample_avgpool(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='2R', negative_slope=0.2):
|
175 |
+
assert len(mode)<4 and mode[0] in ['2', '3'], 'mode examples: 2, 2R, 2BR, 3, ..., 3BR.'
|
176 |
+
kernel_size_pool = int(mode[0])
|
177 |
+
stride_pool = int(mode[0])
|
178 |
+
mode = mode.replace(mode[0], 'AC')
|
179 |
+
pool = conv(kernel_size=kernel_size_pool, stride=stride_pool, mode=mode[0], negative_slope=negative_slope)
|
180 |
+
pool_tail = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode=mode[1:], negative_slope=negative_slope)
|
181 |
+
return sequential(pool, pool_tail)
|
182 |
+
|
183 |
+
|
184 |
+
|
185 |
+
class QFAttention(nn.Module):
|
186 |
+
def __init__(self, in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=True, mode='CRC', negative_slope=0.2):
|
187 |
+
super(QFAttention, self).__init__()
|
188 |
+
|
189 |
+
assert in_channels == out_channels, 'Only support in_channels==out_channels.'
|
190 |
+
if mode[0] in ['R', 'L']:
|
191 |
+
mode = mode[0].lower() + mode[1:]
|
192 |
+
|
193 |
+
self.res = conv(in_channels, out_channels, kernel_size, stride, padding, bias, mode, negative_slope)
|
194 |
+
|
195 |
+
def forward(self, x, gamma, beta):
|
196 |
+
gamma = gamma.unsqueeze(-1).unsqueeze(-1)
|
197 |
+
beta = beta.unsqueeze(-1).unsqueeze(-1)
|
198 |
+
res = (gamma)*self.res(x) + beta
|
199 |
+
return x + res
|
200 |
+
|
201 |
+
|
202 |
+
class FBCNN(nn.Module):
|
203 |
+
def __init__(self, in_nc=3, out_nc=3, nc=[64, 128, 256, 512], nb=4, act_mode='R', downsample_mode='strideconv',
|
204 |
+
upsample_mode='convtranspose'):
|
205 |
+
super(FBCNN, self).__init__()
|
206 |
+
|
207 |
+
self.m_head = conv(in_nc, nc[0], bias=True, mode='C')
|
208 |
+
self.nb = nb
|
209 |
+
self.nc = nc
|
210 |
+
# downsample
|
211 |
+
if downsample_mode == 'avgpool':
|
212 |
+
downsample_block = downsample_avgpool
|
213 |
+
elif downsample_mode == 'maxpool':
|
214 |
+
downsample_block = downsample_maxpool
|
215 |
+
elif downsample_mode == 'strideconv':
|
216 |
+
downsample_block = downsample_strideconv
|
217 |
+
else:
|
218 |
+
raise NotImplementedError('downsample mode [{:s}] is not found'.format(downsample_mode))
|
219 |
+
|
220 |
+
self.m_down1 = sequential(
|
221 |
+
*[ResBlock(nc[0], nc[0], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
|
222 |
+
downsample_block(nc[0], nc[1], bias=True, mode='2'))
|
223 |
+
self.m_down2 = sequential(
|
224 |
+
*[ResBlock(nc[1], nc[1], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
|
225 |
+
downsample_block(nc[1], nc[2], bias=True, mode='2'))
|
226 |
+
self.m_down3 = sequential(
|
227 |
+
*[ResBlock(nc[2], nc[2], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
|
228 |
+
downsample_block(nc[2], nc[3], bias=True, mode='2'))
|
229 |
+
|
230 |
+
self.m_body_encoder = sequential(
|
231 |
+
*[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)])
|
232 |
+
|
233 |
+
self.m_body_decoder = sequential(
|
234 |
+
*[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)])
|
235 |
+
|
236 |
+
# upsample
|
237 |
+
if upsample_mode == 'upconv':
|
238 |
+
upsample_block = upsample_upconv
|
239 |
+
elif upsample_mode == 'pixelshuffle':
|
240 |
+
upsample_block = upsample_pixelshuffle
|
241 |
+
elif upsample_mode == 'convtranspose':
|
242 |
+
upsample_block = upsample_convtranspose
|
243 |
+
else:
|
244 |
+
raise NotImplementedError('upsample mode [{:s}] is not found'.format(upsample_mode))
|
245 |
+
|
246 |
+
self.m_up3 = nn.ModuleList([upsample_block(nc[3], nc[2], bias=True, mode='2'),
|
247 |
+
*[QFAttention(nc[2], nc[2], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
|
248 |
+
|
249 |
+
self.m_up2 = nn.ModuleList([upsample_block(nc[2], nc[1], bias=True, mode='2'),
|
250 |
+
*[QFAttention(nc[1], nc[1], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
|
251 |
+
|
252 |
+
self.m_up1 = nn.ModuleList([upsample_block(nc[1], nc[0], bias=True, mode='2'),
|
253 |
+
*[QFAttention(nc[0], nc[0], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)]])
|
254 |
+
|
255 |
+
|
256 |
+
self.m_tail = conv(nc[0], out_nc, bias=True, mode='C')
|
257 |
+
|
258 |
+
|
259 |
+
self.qf_pred = sequential(*[ResBlock(nc[3], nc[3], bias=True, mode='C' + act_mode + 'C') for _ in range(nb)],
|
260 |
+
torch.nn.AdaptiveAvgPool2d((1,1)),
|
261 |
+
torch.nn.Flatten(),
|
262 |
+
torch.nn.Linear(512, 512),
|
263 |
+
nn.ReLU(),
|
264 |
+
torch.nn.Linear(512, 512),
|
265 |
+
nn.ReLU(),
|
266 |
+
torch.nn.Linear(512, 1),
|
267 |
+
nn.Sigmoid()
|
268 |
+
)
|
269 |
+
|
270 |
+
self.qf_embed = sequential(torch.nn.Linear(1, 512),
|
271 |
+
nn.ReLU(),
|
272 |
+
torch.nn.Linear(512, 512),
|
273 |
+
nn.ReLU(),
|
274 |
+
torch.nn.Linear(512, 512),
|
275 |
+
nn.ReLU()
|
276 |
+
)
|
277 |
+
|
278 |
+
self.to_gamma_3 = sequential(torch.nn.Linear(512, nc[2]),nn.Sigmoid())
|
279 |
+
self.to_beta_3 = sequential(torch.nn.Linear(512, nc[2]),nn.Tanh())
|
280 |
+
self.to_gamma_2 = sequential(torch.nn.Linear(512, nc[1]),nn.Sigmoid())
|
281 |
+
self.to_beta_2 = sequential(torch.nn.Linear(512, nc[1]),nn.Tanh())
|
282 |
+
self.to_gamma_1 = sequential(torch.nn.Linear(512, nc[0]),nn.Sigmoid())
|
283 |
+
self.to_beta_1 = sequential(torch.nn.Linear(512, nc[0]),nn.Tanh())
|
284 |
+
|
285 |
+
|
286 |
+
def forward(self, x, qf_input=None):
|
287 |
+
|
288 |
+
h, w = x.size()[-2:]
|
289 |
+
paddingBottom = int(np.ceil(h / 8) * 8 - h)
|
290 |
+
paddingRight = int(np.ceil(w / 8) * 8 - w)
|
291 |
+
x = nn.ReplicationPad2d((0, paddingRight, 0, paddingBottom))(x)
|
292 |
+
|
293 |
+
x1 = self.m_head(x)
|
294 |
+
x2 = self.m_down1(x1)
|
295 |
+
x3 = self.m_down2(x2)
|
296 |
+
x4 = self.m_down3(x3)
|
297 |
+
x = self.m_body_encoder(x4)
|
298 |
+
qf = self.qf_pred(x)
|
299 |
+
x = self.m_body_decoder(x)
|
300 |
+
qf_embedding = self.qf_embed(qf_input) if qf_input is not None else self.qf_embed(qf)
|
301 |
+
gamma_3 = self.to_gamma_3(qf_embedding)
|
302 |
+
beta_3 = self.to_beta_3(qf_embedding)
|
303 |
+
|
304 |
+
gamma_2 = self.to_gamma_2(qf_embedding)
|
305 |
+
beta_2 = self.to_beta_2(qf_embedding)
|
306 |
+
|
307 |
+
gamma_1 = self.to_gamma_1(qf_embedding)
|
308 |
+
beta_1 = self.to_beta_1(qf_embedding)
|
309 |
+
|
310 |
+
|
311 |
+
x = x + x4
|
312 |
+
x = self.m_up3[0](x)
|
313 |
+
for i in range(self.nb):
|
314 |
+
x = self.m_up3[i+1](x, gamma_3,beta_3)
|
315 |
+
|
316 |
+
x = x + x3
|
317 |
+
|
318 |
+
x = self.m_up2[0](x)
|
319 |
+
for i in range(self.nb):
|
320 |
+
x = self.m_up2[i+1](x, gamma_2, beta_2)
|
321 |
+
x = x + x2
|
322 |
+
|
323 |
+
x = self.m_up1[0](x)
|
324 |
+
for i in range(self.nb):
|
325 |
+
x = self.m_up1[i+1](x, gamma_1, beta_1)
|
326 |
+
|
327 |
+
x = x + x1
|
328 |
+
x = self.m_tail(x)
|
329 |
+
x = x[..., :h, :w]
|
330 |
+
|
331 |
+
return x, qf
|
332 |
+
|
333 |
+
if __name__ == "__main__":
|
334 |
+
x = torch.randn(1, 3, 96, 96)#.cuda()#.to(torch.device('cuda'))
|
335 |
+
fbar=FBAR()
|
336 |
+
y,qf = fbar(x)
|
337 |
+
print(y.shape,qf.shape)
|
packages.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
python3-opencv
|
requirements.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
opencv-python
|
3 |
+
torchvision
|
utils_image.py
ADDED
@@ -0,0 +1,999 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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')
|