forked from hanxf/matchnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchnet.py
68 lines (54 loc) · 2.01 KB
/
matchnet.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
import numpy as np
import caffe
class FeatureNet(caffe.Net):
"""Feature network
"""
def __init__(self, model_file, pretrained_file):
caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)
self.batch_size_ = self.blobs[self.inputs[0]].num
def ComputeFeature(self, inputs):
"""
Compute features for given inputs.
Parameters
----------
inputs: N x 1 x H x W array. N is the number of patches.
W and H should match the input layer's width and height.
Returns
-------
feats: (N x F x 1 x 1) array of features. F is the feature dimension.
"""
# Preprocessing.
in_ = (inputs.astype(np.float32) - 128) / 160
# Compute features.
out_ = self.forward_all(**{self.inputs[0]: in_})
# Reshape features into a 1-D feature vectors.
feats = out_[self.outputs[0]].reshape((len(in_), -1, 1, 1))
return feats
def GetBatchSize(self):
return self.batch_size_
class MetricNet(caffe.Net):
"""Metric Network
"""
def __init__(self, model_file, pretrained_file):
caffe.Net.__init__(self, model_file, pretrained_file, caffe.TEST)
self.batch_size_ = self.blobs[self.inputs[0]].num
def ComputeScore(self, inputs1, inputs2):
"""
Compute matching scores for input pairs.
Parameters
----------
inputs1, inputs2: N x F x 1 x 1 array.
N is the number of patches. F is the feature dimension.
Returns
-------
scores: flatten array with N elements as matching scores.
0: not matching, 1: matching.
"""
# Check the batch size.
assert inputs1.shape[0] == inputs2.shape[0]
in_ = np.concatenate((inputs1, inputs2), axis=1)
out_ = self.forward_all(**{self.inputs[0]: in_})
scores = out_[self.outputs[0]][:, 1]
return scores.flatten()
def GetBatchSize(self):
return self.batch_size_