forked from dips4717/gcn-cnn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_cpu_only.py
More file actions
139 lines (105 loc) · 4.45 KB
/
Copy pathevaluate_cpu_only.py
File metadata and controls
139 lines (105 loc) · 4.45 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
133
134
135
136
137
138
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 20 11:01:07 2019
Compute the performance metrics for graphencoder model
performance metrics includes iou, pixelAccuracy
@author: dipu
"""
import torch
from torchvision import transforms
import torch.nn.functional as F
import pickle
from scipy.spatial.distance import cdist
import numpy as np
import init_paths
from dataloaders.dataloader_test_2 import *
from dataloaders.dataloader_test_2 import RICO_ComponentDataset
import models
import opts_dml
import os
from BoundingBox import BoundingBox
from BoundingBoxes import BoundingBoxes
from utils import mkdir_if_missing, load_checkpoint
from eval_metrics.get_overall_Classwise_IOU import get_overall_Classwise_IOU
from eval_metrics.get_overall_pix_acc import get_overall_pix_acc
def main():
opt = opts_dml.parse_opt()
os.environ["CUDA_VISIBLE_DEVICES"] = opt.gpu_id
onlyGallery = True
opt.use_directed_graph = True
opt.decoder_model = 'strided'
opt.dim =1024
boundingBoxes = getBoundingBoxes_from_info()
model_file = 'trained_models/model_dec_strided_dim1024_ep35.pth'
data_transform = transforms.Compose([ # Not used for 25Channel_images
transforms.Resize([255,127]),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
model = models.create(opt.decoder_model, opt)
#resume = load_checkpoint(model_file)
resume = torch.load(model_file, map_location=torch.device('cpu'))
model.load_state_dict(resume['state_dict'])
#model = model.cuda()
model.eval()
loader = RICO_ComponentDataset(opt, data_transform)
q_feat, q_fnames = extract_features(model, loader, split='query')
g_feat, g_fnames = extract_features(model, loader, split='gallery')
if not(onlyGallery):
t_feat, t_fnames = extract_features(model, loader, split='train')
g_feat = np.vstack((g_feat,t_feat))
g_fnames = g_fnames + t_fnames
q_feat = np.concatenate(q_feat)
g_feat = np.concatenate(g_feat)
distances = cdist(q_feat, g_feat, metric= 'euclidean')
sort_inds = np.argsort(distances)
overallMeanClassIou, _, _ = get_overall_Classwise_IOU(boundingBoxes,sort_inds,g_fnames,q_fnames, topk = [1,5,10])
overallMeanAvgPixAcc, _, _ = get_overall_pix_acc(boundingBoxes,sort_inds,g_fnames,q_fnames, topk = [1,5,10])
print('The overallMeanClassIou = ' + str([ '{:.3f}'.format(x) for x in overallMeanClassIou]) + '\n')
print('The overallMeanAvgPixAcc = ' + str([ '{:.3f}'.format(x) for x in overallMeanAvgPixAcc]) + '\n')
def extract_features(model, loader, split='gallery'):
epoch_done = False
feat = []
fnames = []
c=0
torch.set_grad_enabled(False)
while epoch_done == False:
c+=1
data = loader.get_batch(split)
sg_data = {key: torch.from_numpy(data['sg_data'][key]) for key in data['sg_data']}
x_enc, x_dec = model(sg_data)
x_enc = F.normalize(x_enc)
outputs = x_enc.detach().cpu().numpy()
feat.append(outputs)
fnames += [x['id'] for x in data['infos']]
if data['bounds']['wrapped']:
#print('Extracted features from {} images from {} split'.format(c, split))
epoch_done = True
print('Extracted features from {} images from {} split'.format(len(fnames), split))
return feat, fnames
# prepare bounding boxes information for RICO dataset
def getBoundingBoxes_from_info(info_file = 'data/rico_box_info.pkl'):
allBoundingBoxes = BoundingBoxes()
info = pickle.load(open(info_file, 'rb'))
#files = glob.glob(data_dir+ "*.json")
for imageName in info.keys():
count = info[imageName]['nComponent']
for i in range(count):
box = info[imageName]['xywh'][i]
bb = BoundingBox(
imageName,
info[imageName]['componentLabel'][i],
box[0],
box[1],
box[2],
box[3],
iconClass=info[imageName]['iconClass'],
textButtonClass=info[imageName]['textButtonClass'])
allBoundingBoxes.addBoundingBox(bb)
print('Collected {} bounding boxes from {} images'. format(allBoundingBoxes.count(), len(info) ))
# testBoundingBoxes(allBoundingBoxes)
return allBoundingBoxes
#%%
if __name__ == '__main__':
main()