-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSRCNN.py
More file actions
132 lines (105 loc) · 4.05 KB
/
SRCNN.py
File metadata and controls
132 lines (105 loc) · 4.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# -*- coding: utf-8 -*-
"""Rohitkumarkeswani_200361138_SRCNN.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1srafVxWW4SeAUQcRy4PzjPuE6L_vhMRF
"""
#!pip3 install scipy==1.1.0
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import scipy
from scipy import misc
from scipy import ndimage
import skimage
from skimage import metrics
def imread(path, is_grayscale=True):
"""
Read image from the giving path.
Default value is gray-scale, and image is read by YCbCr format as the paper.
"""
if is_grayscale:
return misc.imread(path, flatten=True, mode='YCbCr').astype(np.float32)
else:
return misc.imread(path, mode='YCbCr').astype(np.float32)
def modcrop(image, scale=3):
"""
To scale down and up the original image, first thing to do is to have no remainder while scaling operation.
We need to find modulo of height (and width) and scale factor.
Then, subtract the modulo from height (and width) of original image size.
There would be no remainder even after scaling operation.
"""
if len(image.shape) == 3:
h, w, _ = image.shape
h = h - np.mod(h, scale)
w = w - np.mod(w, scale)
image = image[0:h, 0:w, :]
else:
h, w = image.shape
h = h - np.mod(h, scale)
w = w - np.mod(w, scale)
image = image[0:h, 0:w]
return image
def preprocess(path, scale=3):
"""
Preprocess single image file
(1) Read original image as YCbCr format (and grayscale as default)
(2) Normalize
(3) Apply image file with bicubic interpolation
Args:
path: file path of desired file
input_: image applied bicubic interpolation (low-resolution)
label_: image with original resolution (high-resolution)
"""
image = imread(path, is_grayscale=True)
label_ = modcrop(image, scale)
# Must be normalized
label_ = label_ / 255.
input_ = ndimage.interpolation.zoom(label_, (1. / scale), prefilter=False)
input_ = ndimage.interpolation.zoom(input_, (scale / 1.), prefilter=False)
return input_, label_
"""Define the model weights and biases
"""
## ------ Add your code here: set the weight of three conv layers
# replace 'None' with your hyper parameter numbers
# conv1 layer with biases: 64 filters with size 9 x 9
# conv2 layer with biases and relu: 32 filters with size 1 x 1
# conv3 layer with biases and NO relu: 1 filter with size 5 x 5
class SRCNN(nn.Module):
def __init__(self):
super(SRCNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=9, padding=4)
self.conv2 = nn.Conv2d(in_channels=64, out_channels=32, kernel_size=1, padding=0)
self.conv3 = nn.Conv2d(in_channels=32, out_channels=1, kernel_size=5, padding=2)
def forward(self, x):
out = F.relu(self.conv1(x))
out = F.relu(self.conv2(out))
out = self.conv3(out)
return out
"""Load the pre-trained model file
"""
model = SRCNN()
model.load_state_dict(torch.load('/content/model.pth'))
model.eval()
"""Read the test image
"""
LR_image, HR_image = preprocess('/content/butterfly_GT.bmp')
# transform the input to 4-D tensor
input_ = np.expand_dims(np.expand_dims(LR_image, axis=0), axis=0)
input_ = torch.from_numpy(input_)
"""Run the model and get the SR image
"""
with torch.no_grad():
output_ = model(input_)
##------ Add your code here: save the LR and SR images and compute the psnr
# hints: use the 'scipy.misc.imsave()' and ' skimage.metrics.peak_signal_noise_ratio()'
SR_image = output_.numpy()
SR_image = np.reshape(SR_image, (255,255))
misc.imsave('/content/LR_image.png', LR_image)
misc.imsave('/content/HR_image.png', HR_image)
misc.imsave('/content/SR_image.png', SR_image)
psnr1 = skimage.metrics.peak_signal_noise_ratio(HR_image, LR_image)
psnr2 = skimage.metrics.peak_signal_noise_ratio(HR_image, SR_image)
print(psnr1)
print(psnr2)