-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric_gen.py
166 lines (139 loc) · 5.81 KB
/
metric_gen.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
from __future__ import print_function, unicode_literals, absolute_import, division
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
import tifffile
import czifile
from csbdeep.utils import normalize
from tqdm import tqdm
from scipy.ndimage import zoom
import argparse
import csv
import glob
import PIL
from PIL import Image
import torchvision
from fastprogress import *
from skimage.measure import compare_ssim, compare_psnr
from pdb import set_trace
def norm_minmse(gt, x, normalize_gt=True):
"""
normalizes and affinely scales an image pair such that the MSE is minimized
Parameters
----------
gt: ndarray
the ground truth image
x: ndarray
the image that will be affinely scaled
normalize_gt: bool
set to True of gt image should be normalized (default)
Returns
-------
gt_scaled, x_scaled
"""
if normalize_gt:
gt = normalize(gt, 0.1, 99.9, clip=False).astype(np.float32, copy = False)
x = x.astype(np.float32, copy=False) - np.mean(x)
gt = gt.astype(np.float32, copy=False) - np.mean(gt)
scale = np.cov(x.flatten(), gt.flatten())[0, 1] / np.var(x.flatten())
return gt, scale * x
def save_stats(stats, save_dir):
with open(save_dir, 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(stats)
csvFile.close()
def slice_process(x1, x2, y):
if len(x1.shape) == 3: x1 = x1[:,:,0]
if len(x2.shape) == 3: x2 = x2[:,:,0]
if len(y.shape) == 3: y = y[:,:,0]
# a scaled and shifted version of pred and bilinear
x1 = 2*x1 + 100
x2 = 2*x2 + 100
# normalize/scale images
(y_norm1, x1_norm) = norm_minmse(y, x1)
(y_norm2, x2_norm) = norm_minmse(y, x2)
# calulate psnr and ssim of the normalized/scaled images
psnr1 = compare_psnr(*(y_norm1, x1_norm), data_range = 1.)
psnr2 = compare_psnr(*(y_norm2, x2_norm), data_range = 1.)
ssim1 = compare_ssim(*(y_norm1, x1_norm), data_range = 1.)
ssim2 = compare_ssim(*(y_norm2, x2_norm), data_range = 1.)
return psnr1, ssim1, psnr2, ssim2, y_norm1, x1_norm, y_norm2, x2_norm
def stack_process(pred, bilinear, gt, offset_frames=0):
stack_pred = PIL.Image.open(pred)
stack_bilinear = PIL.Image.open(bilinear)
stack_gt = PIL.Image.open(gt)
stem = Path(pred).stem
frames = stack_pred.n_frames
stack_psnr = []
stack_lpsnr = []
stack_ssim = []
stack_lssim = []
stack_name = []
#y_norm1s = []
#x1_norms = []
#y_norm2s = []
#x2_norms = []
for i in range(frames):
stack_pred.seek(i)
stack_bilinear.seek(i) if frames == 1 else stack_bilinear.seek(i+offset_frames)
stack_gt.seek(i) if frames == 1 else stack_gt.seek(i+offset_frames)
x1 = np.array(stack_pred).astype(np.float32)
x2 = np.array(stack_bilinear).astype(np.float32)
y = np.array(stack_gt).astype(np.float32)
psnr, ssim, l_psnr, l_ssim, y_norm1, x1_norm, y_norm2, x2_norm = slice_process(x1, x2, y)
stack_psnr.append(psnr)
stack_lpsnr.append(l_psnr)
stack_ssim.append(ssim)
stack_lssim.append(l_ssim)
stack_name.append(f'{stem}_z{i}.tif')
#y_norm1s.append(np.array(y_norm1).copy())
#x1_norms.append(np.array(x1_norm).copy())
#y_norm2s.append(np.array(y_norm2).copy())
#x2_norms.append(np.array(x2_norm).copy())
#tifffile.imsave(str(exp_dir/f"{stem}_GTnormtopred.tif"), np.stack(y_norm1s).astype(np.float32))
#tifffile.imsave(str(exp_dir/f"{stem}_prednorm.tif"), np.stack(x1_norms).astype(np.float32))
#tifffile.imsave(str(exp_dir/f"{stem}_GTnormtobilinear.tif"), np.stack(y_norm2s).astype(np.float32))
#tifffile.imsave(str(exp_dir/f"{stem}_bilinearnorm.tif"), np.stack(x2_norms).astype(np.float32))
return stack_name, stack_psnr,stack_ssim,stack_lpsnr,stack_lssim
def metric_gen(predset, testset, bilinset, offset_frames):
save_dir = f'stats.csv'
pred_dir = Path(predset)
bilinear_dir = Path(bilinset)
gt_dir = Path(testset)
pred_list = list(pred_dir.glob(f'*.tif'))
bilinear_list = list(bilinear_dir.glob(f'*.tif'))
gt_list = list(gt_dir.glob(f'*.tif'))
pred_list.sort()
bilinear_list.sort()
gt_list.sort()
names = ['name']
ssims = ['ssims']
l_ssims = ['l_ssims']
psnrs = ['psnrs']
l_psnrs = ['l_psnrs']
for p, l, t in progress_bar(list(zip(pred_list, bilinear_list, gt_list))):
print(f'pred: {p}')
print(f'bilinear: {l}')
print(f'gt: {t}')
print(f'offset_frame: {offset_frames}')
stack_name,stack_psnr,stack_ssim,stack_lpsnr,stack_lssim = stack_process(p,l,t,offset_frames)
names = np.concatenate((names, stack_name), out=None)
psnrs = np.concatenate((psnrs, stack_psnr), out=None)
l_psnrs = np.concatenate((l_psnrs, stack_lpsnr), out=None)
ssims = np.concatenate((ssims, stack_ssim), out=None)
l_ssims = np.concatenate((l_ssims, stack_lssim), out=None)
stats = zip(names, ssims, l_ssims, psnrs, l_psnrs)
save_stats(stats, save_dir)
if __name__ == '__main__':
np.random.seed(32)
parser = argparse.ArgumentParser(description='')
parser.add_argument('-e', '--experiment', type = str, default = "/home/alaa/Dropbox/BPHO Staff/USF/EM/testing/HR/real-world_SEM/")
parser.add_argument('-p', '--predset', type = str, default = "/home/alaa/Dropbox/BPHO Staff/USF/EM/testing/emsynth_005_unet/real-world_SEM/")
parser.add_argument('-b', '--bilinset', type = str, default = "/home/alaa/Dropbox/BPHO Staff/USF/EM/testing/LR-Bilinear/real-world_SEM/")
args = parser.parse_args()
predset = args.predset
testset = args.experiment
bilinset = args.bilinset
# stats_dir = Path('stats/')
offset_frames = 2 if 'multi' in predset else 0
metric_gen(predset, testset, bilinset, offset_frames)