-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathEval_WiCo_PD.py
181 lines (162 loc) · 7.08 KB
/
Eval_WiCo_PD.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
import os
import cv2
import time
import datetime
import numpy as np
import torch.autograd
from skimage import io
from scipy import stats
import torch.nn.functional as F
from torch.utils.data import DataLoader
from utils.loss import CrossEntropyLoss2d
from utils.utils import accuracy, intersectionAndUnion, AverageMeter, CaclTP
# Choose model and data
##################################################
from datasets import PD_WiCo as PD
from models.WiCoNet import WiCoNet as Net
NET_NAME = 'WiCoNet_3hw4L'
DATA_NAME = 'PD'
##################################################
# Change testing parameters here
working_path = os.path.abspath('.')
args = {
'gpu': True,
's_class': 0,
'val_batch_size': 1,
'size_local': 256,
'size_context': 256 * 3,
'data_dir': 'YOUR_DATA_DIR',
'load_path': 'YOUR_DATA_DIRSAVED_MODEL_CHECKPOINT.pth'
}
def norm_gray(x, out_range=(0, 255)):
# x=x*(x>0)
domain = np.min(x), np.max(x)
y = (x - (domain[1] + domain[0]) / 2) / (domain[1] - domain[0] + 1e-10)
y = y * (out_range[1] - out_range[0]) + (out_range[1] + out_range[0]) / 2
return y.astype('uint8')
def draw_rectangle(img, pos='boundary', color=(0, 255, 0), thick=2, text='context window'):
h, w, c = img.shape
if pos=='boundary':
start_pos = (0,0)
end_pos = (h-1, w-1)
elif pos == 'center':
start_pos = (h//2-32, w//2-32)
end_pos = (h//2+32, w//2+32)
cv2.rectangle(img, start_pos, end_pos, color, thick)
if pos=='boundary':
cv2.putText(img, text, (start_pos[0]+15,start_pos[1]+15), cv2.FONT_HERSHEY_PLAIN, 1.2, color)
elif pos == 'center':
cv2.putText(img, text, (start_pos[0]-24,start_pos[1]-5), cv2.FONT_HERSHEY_PLAIN, 1.2, color)
return img
def main():
net = Net(5, num_classes=RS.num_classes+1, size_context=args['crop_size_global'], size_local=args['crop_size_local']).cuda()
net.load_state_dict(torch.load(args['chkpt_path']))#, strict = False
net = net.cuda()
net.eval()
print(NET_NAME+' Model loaded.')
pred_path = os.path.join(args['data_dir'], 'Eval', NET_NAME)
if not os.path.exists(pred_path): os.makedirs(pred_path)
info_txt_path = os.path.join(pred_path, 'info.txt')
f = open(info_txt_path, 'w+')
val_set = PD.Loader(args['data_dir'], 'test', sliding_crop=True, crop_size_global=args['crop_size_global'], crop_size_local=args['crop_size_local'])
val_loader = DataLoader(val_set, batch_size=args['val_batch_size'], num_workers=4, shuffle=False)
predict(net, val_loader, pred_path, args, f)
f.close()
def predict(net, pred_loader, pred_path, f_out=None):
acc_meter = AverageMeter()
TP_meter = AverageMeter()
pred_meter = AverageMeter()
label_meter = AverageMeter()
Union_meter = AverageMeter()
output_info = f_out is not None
for vi, data in enumerate(pred_loader):
with torch.no_grad():
img_s, label_s, img, label = data
if args['gpu']:
img_s = img_s.cuda().float()
img = img.cuda().float()
label = label.cuda().float()
output, aux = net(img_s, img)
output = output.detach().cpu()
pred = torch.argmax(output, dim=1)
pred = pred.numpy().squeeze()
if args['s_class']:
class_map = F.softmax(output, dim=1)[:, args['s_class'], :, :]
class_map = class_map.numpy().squeeze()
class_map = norm_gray(class_map)
label = label.detach().cpu().numpy()
acc, _ = accuracy(pred, label)
acc_meter.update(acc)
pred_color = RS.Index2Color(pred)
img = img.detach().cpu().numpy().squeeze().transpose((1, 2, 0))[:,:,:3]
img = norm_gray(img)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# img = draw_rectangle(img)
# img = draw_rectangle(img, pos='center', color=(0, 255, 255), thick=2, text='local window')
# label_color = PD.Index2Color(label).squeeze()
pred_name = os.path.join(pred_path, '%d_WiC.png'%vi)
io.imsave(pred_name, pred_color)
# img_name = os.path.join(pred_path, '%d_img.png'%vi)
# label_name = os.path.join(pred_path, '%d_label.png'%vi)
# io.imsave(label_name, label_color)
if args['s_class']:
saliency_map = cv2.applyColorMap(class_map, cv2.COLORMAP_JET)
pred_name = os.path.join(pred_path, '%d_WiC_saliency.png'%vi)
saliency_map = (img*0.5 + saliency_map*0.5).astype('uint8')
io.imsave(pred_name, saliency_map)
TP, pred_hist, label_hist, union_hist = CaclTP(pred, label, RS.num_classes)
TP_meter.update(TP)
pred_meter.update(pred_hist)
label_meter.update(label_hist)
Union_meter.update(union_hist)
print('Eval num %d/%d, Acc %.2f'%(vi, len(pred_loader), acc*100))
if output_info:
f_out.write('Eval num %d/%d, Acc %.2f\n'%(vi, len(pred_loader), acc*100))
precision = TP_meter.sum / (label_meter.sum + 1e-10) + 1e-10
recall = TP_meter.sum / (pred_meter.sum + 1e-10) + 1e-10
F1 = [stats.hmean([pre, rec]) for pre, rec in zip(precision, recall)]
F1 = np.array(F1)
IoU = TP_meter.sum / Union_meter.sum
IoU = np.array(IoU)
print(output.shape)
print('Acc %.2f'%(acc_meter.avg*100))
avg_F = F1[:-1].mean()
mIoU = IoU[:-1].mean()
print('Avg F1 %.2f'%(avg_F*100))
print(np.array2string(F1 * 100, precision=4, separator=', ', formatter={'float_kind': lambda x: "%.2f" % x}))
print('mIoU %.2f'%(mIoU*100))
print(np.array2string(IoU * 100, precision=4, separator=', ', formatter={'float_kind': lambda x: "%.2f" % x}))
if output_info:
f_out.write('Acc %.2f\n'%(acc_meter.avg*100))
f_out.write('Avg F1 %.2f\n'%(avg_F*100))
f_out.write(np.array2string(F1 * 100, precision=4, separator=', ', formatter={'float_kind': lambda x: "%.2f" % x}))
f_out.write('\nmIoU %.2f\n'%(mIoU*100))
f_out.write(np.array2string(IoU * 100, precision=4, separator=', ', formatter={'float_kind': lambda x: "%.2f" % x}))
return avg_F
def AccEval(outputs, labels):
acc_meter = AverageMeter()
TP_meter = AverageMeter()
pred_meter = AverageMeter()
label_meter = AverageMeter()
for vi in range(len(labels)):
label = labels[vi]
output = outputs[vi].detach().cpu()
_, pred = torch.max(output, dim=0)
pred = pred.numpy()
acc, _ = accuracy(pred, label)
acc_meter.update(acc)
TP, pred_hist, label_hist = CaclTP(pred, label, RS.num_classes)
TP_meter.update(TP)
pred_meter.update(pred_hist)
label_meter.update(label_hist)
precision = TP_meter.sum / (label_meter.sum + 1e-10) + 1e-10
recall = TP_meter.sum / (pred_meter.sum + 1e-10) + 1e-10
F1 = [stats.hmean([pre, rec]) for pre, rec in zip(precision, recall)]
F1 = np.array(F1)
print('Acc %.2f'%(acc_meter.avg*100))
print(np.array2string(F1 * 100, precision=4, separator=', ', formatter={'float_kind': lambda x: "%.2f" % x}))
avg_F = np.array(F1[:-1]).mean()
print(avg_F*100)
return acc_meter.avg
if __name__ == '__main__':
main()