-
Notifications
You must be signed in to change notification settings - Fork 3
/
matcher.py
165 lines (137 loc) · 5.95 KB
/
matcher.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
"""
===========
matcher.py
===========
五种基本匹配算法(https://github.com/JinlongLi2016/point_matching)
"""
__author__ = 'JinlongLi2016'
__licence__ = 'MIT'
__versin__ = '1.0'
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.figure as mpfig
import seaborn as sns
class Matcher(object):
"""docstring for Match"""
def __init__(self, obj_win, search_img):
super(Matcher, self).__init__()
self._obj_win = obj_win
self._search_img = search_img
self._win_size = 9
def get_best_coords_matched(self, criteria = 'corr_func'):
'''从 ._search_img 中 找出搜索窗口在 'critera' 标准下最好
的坐标.
请注意: 比较时 最好的 得分最高,因此在编写 criteria函数时候,
越好的搜索窗口返回的得分是最高的.避免在某个标准下好的窗口得分
低.比如,差平方和 标准
返回 匹配最好的坐标(x, y)
'''
m, n = self._search_img.shape
best_x, best_y = 0, 0
best_value = float('-inf')
h_w = self._win_size//2
for i in range(self._win_size//2, m -self._win_size//2 ):
for j in range(self._win_size//2, n -self._win_size//2 ):
search_win = np.copy( self._search_img[i-h_w:i+h_w+1, j-h_w:j+h_w+1] )
if criteria == 'corr_func':
score = self.correlation_func(self._obj_win, search_win)
elif criteria == 'corr_effi':
score = self.correlation_effi(self._obj_win, search_win)
elif criteria == 'cov_func':
score = self.covariance_func(self._obj_win, search_win)
elif criteria == 'mod1':
score = self.mod1_of_diffrence(self._obj_win, search_win)
elif criteria == 'mod2':
score = self.mod2_of_difference(self._obj_win, search_win)
else:
raise ValueError("parameter error, %s not wrotten"%criteria)
if score > best_value:
best_x, best_y = i, j
best_value = score
return best_x, best_y
def correlation_func(self, obj_win, search_win):
"""Correlation fucntion"""
s = np.multiply(obj_win, search_win).sum()
return s
def covariance_func(self, obj_win, search_win):
'''Covariance function '''
assert obj_win.shape == search_win.shape
m, n = obj_win.shape
obj_win = obj_win - obj_win.sum() / (m * n)
search_win = search_win - search_win.sum() / (m * n)
s = np.multiply(obj_win, search_win).sum()
return s
def correlation_effi(self, obj_win, search_win):
'''Correlation efficient'''
assert obj_win.shape == search_win.shape, "windows' shape not matched"
C = self.covariance_func(obj_win, search_win)
ro = C / (obj_win.std() * search_win.std() )
return abs(ro)
def mod2_of_difference(self, obj_win, search_win):
'''sum of the square of the difference of two vector'''
assert obj_win.shape == search_win.shape, "windows' shape not matched"
diff = (obj_win - search_win).flatten()
return - np.dot(diff, diff) #
def mod1_of_diffrence(self, obj_win, search_win):
'''sum of the absolute value of the difference of 2 vectors'''
assert obj_win.shape == search_win.shape, "windows' shape not matched"
diff = (obj_win - search_win).flatten()
return -abs(diff).sum()# some comments
class MatcherTester(object):
"""docstring for MatcherTester"""
def __init__(self, obj_points_fname = 'data/1BAK_points.txt',
obj_img_fname = 'data/1BAK.bmp',
search_img_fname = 'data/2BAK.bmp'):
super(MatcherTester, self).__init__()
self._obj_points_fname = obj_points_fname
self._obj_img_fname = obj_img_fname
self._search_img_fname = search_img_fname
self._obj_img = mpimg.imread(self._obj_img_fname)
self._search_img = mpimg.imread(self._search_img_fname)
self._win_size = 9
self.get_points()
def get_points(self):
"""从文件中读取 目标点的坐标"""
f = open(self._obj_points_fname)
ob = f.readlines()
# 前后有可能有空格
ob = [l for l in ob if len(l)>5]
ob = [l.split() for l in ob]
m, n = np.array(ob).shape
for i in range(m):
for j in range(n):
ob[i][j] = int(ob[i][j])
ob = np.array(ob)
self._coord_name = ob[:, 0]
self._coord_poi = ob[:, 1:3]
def matched_coords(self, criteria = 'corr_func'):
m = len(self._coord_name)
best_pois = []
for i in range(m): # 对每一个点,构建一个matcher类
poi_x, poi_y = self._coord_poi[i]
h_w = self._win_size//2
# print([poi_y-h_w,poi_y+h_w+1, poi_x-h_w, poi_x+h_w+1])
a = Matcher(self._obj_img[poi_y-h_w:poi_y+h_w+1, poi_x-h_w:poi_x+h_w+1],
self._search_img)
best_poi = a.get_best_coords_matched(criteria)
best_pois.append(best_poi)
return best_pois
def plot_matched_points(self, criteria = 'corr_func'):
best_pois = self.matched_coords(criteria)
plt.figure()
plt.imshow(self._search_img, cmap = 'Greys_r')
for p, i in zip(best_pois, range(len(best_pois))):
plt.scatter(p[1], p[0])
plt.annotate(s = str(self._coord_name[i]), xy=(p[1], p[0]))
plt.title(criteria+'_picture')
plt.savefig('data/matchedpic_' + criteria+'_.jpg')
# plt.show()savefig before show() !!!
def main():
criteria_list = ['corr_func', 'corr_effi', 'cov_func', 'mod1', 'mod2']
a = MatcherTester()
for c in criteria_list:
a.plot_matched_points(c)
if __name__ == '__main__':
# 修改 _win_size 参数
main()