-
Notifications
You must be signed in to change notification settings - Fork 94
/
rerank.py
349 lines (233 loc) · 10.5 KB
/
rerank.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import sys, os,cv2, time, random
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
import math
from params import get_params
import pickle
params = get_params()
from sklearn.preprocessing import normalize
# Add Faster R-CNN module to pythonpath
sys.path.insert(0, os.path.join(params['fast_rcnn_path'],'caffe-fast-rcnn', 'python'))
sys.path.insert(0, os.path.join(params['fast_rcnn_path'],'lib'))
import caffe
from fast_rcnn.config import cfg
import test as test_ops
class Reranker():
def __init__(self,params):
self.dataset= params['dataset']
self.image_path = params['database_images']
self.dimension = params['dimension']
self.layer = params['layer']
self.top_n = params['num_rerank']
self.reranking_path = params['reranking_path']
self.REG_BOXES = params['use_regressed_boxes']
self.pooling = params['pooling']
self.stage = params['stage']
self.N_QE = params['N_QE']
self.class_scores = params['use_class_scores']
with open(params['frame_list'],'r') as f:
self.database_list = f.read().splitlines()
with open(params['query_list'],'r') as f:
self.query_names = f.read().splitlines()
# Distance type
self.dist_type = params['distance']
# Where to store the rankings
self.rankings_dir = params['rankings_dir']
# Init network
if params['gpu']:
caffe.set_mode_gpu()
caffe.set_device(0)
else:
caffe.set_mode_cpu()
cfg.TEST.HAS_RPN = True
self.net = caffe.Net(params['net_proto'], params['net'], caffe.TEST)
self.queries = params['query_names']
# List of queries
if self.pooling is 'sum':
# PCA Models
if self.dataset is 'paris':
self.pca = pickle.load(open(params['pca_model'] + '_oxford.pkl', 'rb'))
elif self.dataset is 'oxford':
self.pca = pickle.load(open(params['pca_model'] + '_paris.pkl', 'rb'))
def extract_feat_image(self,image):
im = cv2.imread(image)
scores, boxes = test_ops.im_detect(self.net, im, boxes = None,REG_BOXES=self.REG_BOXES)
layer_roi = 'pool5'
feat = self.net.blobs[layer_roi].data
return feat,boxes,scores
def read_ranking(self,query):
with open(os.path.join(self.rankings_dir,os.path.basename(query.split('_query')[0]) +'.txt'),'r') as f:
ranking = f.read().splitlines()
return ranking
def query_info(self,filename):
'''
For oxford and paris, get query frame and box
'''
data = np.loadtxt(filename, dtype="str")
if self.dataset is 'paris':
query = data[0]
elif self.dataset is 'oxford':
query = data[0].split('oxc1_')[1]
bbx = data[1:].astype(float).astype(int)
if self.dataset is 'paris':
query = os.path.join(self.image_path,query.split('_')[1],query + '.jpg')
elif self.dataset is 'oxford':
query = os.path.join(self.image_path,query + '.jpg')
return query, bbx
def get_query_local_feat(self,query,box=None):
'''
Extract local query feature using bbx
'''
if box is None:
# For paris and oxford
query,bbx = self.query_info(query)
else:
# locations are provided
xmin = box[0]
ymin = box[1]
xmax = box[2]
ymax = box[3]
im = cv2.imread(query)
height = np.shape(im)[0]
width = np.shape(im)[1]
# Forward pass
scores, boxes = test_ops.im_detect(self.net, im, boxes = None)
# Get conv5 layer
feat = self.net.blobs[self.layer].data.squeeze()
# Get the image/feature ratio
mult_h = float(np.shape(feat)[1])/height
mult_w = float(np.shape(feat)[2])/width
# Resize the bounding box to feature size
if box is None:
# Adjust query bounding box to feature space
bbx[0] *= mult_w
bbx[2] *= mult_w
bbx[1] *= mult_h
bbx[3] *= mult_h
else:
bbx = [int(math.floor(xmin*mult_w)),int(math.floor(ymin*mult_h)),int(math.ceil(xmax*mult_w)),int(math.ceil(ymax*mult_h))]
# Crop local features with bounding box
local_feat = feat[:,bbx[1]:bbx[3],bbx[0]:bbx[2]]
# sum pool
if self.pooling is 'sum':
local_feat = np.sum(np.sum(local_feat,axis=1),axis=1)
else:
local_feat = np.max(np.max(local_feat,axis=1),axis=1)
return local_feat
def rerank_one_query(self,query,num_queries):
# Init query feat vector
query_feats = np.zeros((self.dimension))
for i in np.arange(num_queries)+1:
query_ = query
query_name = os.path.basename(query).rsplit('_',2)[0]
# Generate query feature and add it to matrix
query_feats += self.get_query_local_feat(query_)
query_feats/=num_queries
query_feats = query_feats.reshape(-1, 1)
if self.stage is 'rerank2nd':
# second stage of reranking. taking N locations at top N ranking as queries...
with open(os.path.join(self.reranking_path,os.path.basename(query.split('_query')[0]) + '.pkl') ,'rb') as f:
distances = pickle.load(f)
locations = pickle.load(f)
frames = pickle.load(f)
class_ids = pickle.load(f)
frames_sorted = np.array(frames)[np.argsort(distances)]
locations_sorted = np.array(locations)[np.argsort(distances)]
for i_qe in range(self.N_QE):
query_feats +=self.get_query_local_feat(frames_sorted[i_qe],locations_sorted[i_qe])
query_feats/=(self.N_QE+1)
query_feats = query_feats.T
query_feats = normalize(query_feats)
if self.pooling is 'sum':
# Apply PCA
query_feats = self.pca.transform(query_feats)
query_feats = normalize(query_feats)
# Read baseline ranking
ranking = self.read_ranking(query)
# Rerank
distances,locations, frames,class_ids = self.rerank_top_n(query_feats,ranking,query_name)
with open(os.path.join(self.reranking_path,os.path.basename(query.split('_query')[0]) + '.pkl') ,'wb') as f:
pickle.dump(distances,f)
pickle.dump(locations,f)
pickle.dump(frames,f)
pickle.dump(class_ids,f)
# Write new ranking to disk
self.write_rankings(query,ranking,distances)
def rerank_top_n(self,query_feats,ranking,query_name):
distances = []
locations = []
frames = []
class_ids = []
#query_feats = query_feats.T
# query class (+1 because class 0 is the background)
cls_ind = np.where(np.array(self.queries) == str(query_name))[0][0] + 1
for im_ in ranking[0:self.top_n]:
if self.dataset is 'paris':
frame_to_read = os.path.join(self.image_path,im_.split('_')[1],im_ + '.jpg')
elif self.dataset is 'oxford':
frame_to_read = os.path.join(self.image_path,im_ + '.jpg')
frames.append(frame_to_read)
# Get features of current element
feats,boxes,scores = self.extract_feat_image(frame_to_read)
# we rank based on class scores
if self.class_scores:
scores = feats[:,cls_ind]
# position with highest score for that class
best_pos = np.argmax(scores)
# array of boxes with higher score for that class
best_box_array = boxes[best_pos,:]
# single box with max score for query class
best_box = best_box_array[4*cls_ind:4*(cls_ind + 1)]
# the actual score
distances.append(np.max(scores))
locations.append(best_box)
class_ids.append(cls_ind)
else:
if self.pooling is 'sum':
# pca transform
feats = np.sum(np.sum(feats,axis=2),axis=2)
feats = normalize(feats)
feats = self.pca.transform(feats)
feats = normalize(feats)
else:
feats = np.max(np.max(feats,axis=2),axis=2)
feats = normalize(feats)
# Compute distances
dist_array = pairwise_distances(query_feats,feats,self.dist_type, n_jobs=-1)
# Select minimum distance
distances.append(np.min(dist_array))
# Array of boxes with min distance
idx = np.argmin(dist_array)
# Select array of locations with minimum distance
best_box_array = boxes[idx,:]
# Discard background score
scores = scores[:,1:]
# Class ID with max score .
cls_ind = np.argmax(scores[idx,:])
class_ids.append(cls_ind+1)
# Select the best box for the best class
best_box = best_box_array[4*cls_ind:4*(cls_ind + 1)]
locations.append(best_box)
return distances,locations, frames, class_ids
def rerank(self):
iter_ = self.query_names
num_queries = 1
i = 0
for query in iter_:
print "Reranking for query", i, "out of", len(iter_), '...'
i+=1
self.rerank_one_query(query,num_queries)
def write_rankings(self,query,ranking,distances):
if self.class_scores:
new_top_r = list(np.array(ranking[0:self.top_n])[np.argsort(distances)[::-1]])
else:
new_top_r = list(np.array(ranking[0:self.top_n])[np.argsort(distances)])
ranking[0:self.top_n] = new_top_r
savefile = open(os.path.join(self.rankings_dir,os.path.basename(query.split('_query')[0]) +'.txt'),'w')
for res in ranking:
savefile.write(os.path.basename(res).split('.jpg')[0] + '\n')
savefile.close()
if __name__== '__main__':
params = get_params()
RR = Reranker(params)
RR.rerank()