-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
200 lines (141 loc) · 5.2 KB
/
utils.py
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@Useway : 辅助函数
@File : utils.py
@Time : 2020/12/31 16:26:28
@Author : Chen Zhuang
@Version : 1.0
@Contact : whut_chenzhuang@163.com
@Time: 2020/12/31 16:26:28
'''
from pathlib import Path
from PIL import Image
import numpy as np
import torch.nn as nn
import torch
from matplotlib import pyplot as plt
from G import OUT_DIR
import scipy.io as io
import h5py
from torch.nn.functional import interpolate
def save_cave_data():
# 生成{train val test}.npy 文件
path = Path('/home/yons/data1/chenzhuang/HSI-SR/DataSet/CAVE')
data = np.zeros((32,31,512,512))
for i,p in enumerate(path.iterdir()) :
print(p)
for j in range(31):
img_path = p.joinpath(p.parts[-1],p.parts[-1]+'_{:0>2d}.png'.format(j+1))
# print(img_path)
img = Image.open(img_path)
img = np.array(img)
# 有特殊shape的图片
if len(img.shape) != 2:
data[i][j] = img[:,:,0]
if len(img.shape) == 2:
data[i][j] = img
# print((i,j))
print(data[:20].shape,data[20:26].shape,data[26:].shape)
np.save('train.npy',data[:20])
np.save('val.npy',data[20:26])
np.save('test.npy',data[26:])
def calc_psnr(img1, img2):
return 10. * torch.log10((255.0 **2)/ torch.mean((img1 - img2) ** 2))
def PSNR_GPU(img1, img2):
mpsnr = 0
for l in range(img1.size()[1]):
mpsnr += 10. * torch.log10(1. / torch.mean((img1[:,l,:,:] - img2[:,l,:,:]) ** 2))
return mpsnr / img1.size()[1]
# return 10. * torch.log10((torch.max(img1)**2) / torch.mean((img1 - img2) ** 2))
def SAM(pred, gt):
pred = pred.numpy()
gt = gt.numpy()
eps = 2.2204e-16
pred[np.where(pred==0)] = eps
gt[np.where(gt==0)] = eps
nom = sum(pred*gt)
denom1 = sum(pred*pred)**0.5
denom2 = sum(gt*gt)**0.5
sam = np.real(np.arccos(nom.astype(np.float32)/(denom1*denom2+eps)))
sam[np.isnan(sam)]=0
sam_sum = np.mean(sam)*180/np.pi
return sam_sum
def plot():
path = '/home/yons/data1/chenzhuang/HSI-SR/GAN-HSI-SR/icvl_train.log'
psnr = []
sam = []
with open(path,'r') as f:
for line in f.readlines():
line = line.strip()
if 'val averagr psnr : ' in line:
line = line.split(' ')
psnr.append(float(line[-4]))
sam.append(float(line[-1]))
epochs = [i for i in range(len(psnr))]
fib_size = (5,4)
fon_size = 12
plt.figure(figsize=fib_size)
plt.title('sam of every epoch',fontsize=fon_size)
plt.xlabel('epoch',fontsize=fon_size)
plt.ylabel('sam', fontsize=fon_size)
plt.plot(epochs, sam, 'k.')
plt.grid(True, linestyle = "-.", color = "k", linewidth = "1.1")
plt.savefig(OUT_DIR.joinpath('icvl_sam.png'))
plt.figure(figsize=fib_size)
plt.title('psnr of every epoch',fontsize=fon_size)
plt.xlabel('epoch',fontsize=fon_size)
plt.ylabel('psnr', fontsize=fon_size)
plt.plot(epochs, psnr, 'k.')
plt.grid(True, linestyle = "-.", color = "k", linewidth = "1.1")
plt.savefig(OUT_DIR.joinpath('icvl_psnr.png'))
def save_mat(l=31,w=144,h=144,fis=144):
path = '/home/yons/data1/chenzhuang/HSI-SR/GAN-HSI-SR/weight/icvl_test_fake_hr.pth'
base_path = Path('/home/yons/data1/chenzhuang/HSI-SR/GAN-HSI-SR/data')
data = torch.load(path)
count = 0
for i in range(8):
img = torch.zeros([31,144*9,144*8])
for x in range(0, 1372-fis, fis):
for y in range(0, 1174-fis, fis):
img[:,x:x+fis,y:y+fis] = data[count]
count += 1
img = interpolate(
img.reshape(1,img.shape[0],img.shape[1],img.shape[2]),
scale_factor=1,
mode='bicubic'
)
img = torch.squeeze(img)
img = img.numpy()
img *= (255)
img = img.astype(np.uint8)
im = Image.fromarray(img[27])
im = im.rotate(180)
im.save(base_path.joinpath('process_icvl_img{}.png'.format(i)))
io.savemat(base_path.joinpath('process_icvl_img{}.mat'.format(i)),{'data':img})
# save_mat()
def get_paths():
PATH = '/home/yons/data1/chenzhuang/HSI-SR/DataSet/ICVL/'
train_paths = []
val_paths = []
test_paths = []
with open(PATH + 'train_name.txt', 'r') as f:
for i in f.readlines():
train_paths.append(PATH + i.strip())
with open(PATH + 'val_name.txt', 'r') as f:
for i in f.readlines():
val_paths.append(PATH + i.strip())
with open(PATH + 'test_name.txt', 'r') as f:
for i in f.readlines():
test_paths.append(PATH + i.strip())
return train_paths, val_paths, test_paths
def save_icvl():
train_paths, val_paths, test_paths = get_paths()
train_data = np.zeros((len(train_paths,31,144,144)))
val_data = np.zeros((len(val_paths,31,144,144)))
test_data = np.zeros((len(test_paths,31,144,144)))
for i in range(len(train_paths)):
img = h5py.File(paths[i], 'r')['rad']
img = np.array(img)
img /= 4095.0
pass