-
Notifications
You must be signed in to change notification settings - Fork 25
/
dsift.py
208 lines (191 loc) · 7.59 KB
/
dsift.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
'''
dsift.py: this function implements some basic functions that
does dense sift feature extraction.
The descriptors are defined in a similar way to the one used in
Svetlana Lazebnik's Matlab implementation, which could be found
at:
http://www.cs.unc.edu/~lazebnik/
Yangqing Jia, [email protected]
'''
import numpy as np
from scipy import signal
from matplotlib import pyplot
# sift features
Nangles = 8
Nbins = 4
Nsamples = Nbins**2
alpha = 9.0
angles = np.array(range(Nangles))*2.0*np.pi/Nangles
def gen_dgauss(sigma):
'''
generating a derivative of Gauss filter on both the X and Y
direction.
'''
fwid = np.int(2*np.ceil(sigma))
G = np.array(range(-fwid,fwid+1))**2
G = G.reshape((G.size,1)) + G
G = np.exp(- G / 2.0 / sigma / sigma)
G /= np.sum(G)
GH,GW = np.gradient(G)
GH *= 2.0/np.sum(np.abs(GH))
GW *= 2.0/np.sum(np.abs(GW))
return GH,GW
class DsiftExtractor:
'''
The class that does dense sift feature extractor.
Sample Usage:
extractor = DsiftExtractor(gridSpacing,patchSize,[optional params])
feaArr,positions = extractor.process_image(Image)
'''
def __init__(self, gridSpacing, patchSize,
nrml_thres = 1.0,\
sigma_edge = 0.8,\
sift_thres = 0.2):
'''
gridSpacing: the spacing for sampling dense descriptors
patchSize: the size for each sift patch
nrml_thres: low contrast normalization threshold
sigma_edge: the standard deviation for the gaussian smoothing
before computing the gradient
sift_thres: sift thresholding (0.2 works well based on
Lowe's SIFT paper)
'''
self.gS = gridSpacing
self.pS = patchSize
self.nrml_thres = nrml_thres
self.sigma = sigma_edge
self.sift_thres = sift_thres
# compute the weight contribution map
sample_res = self.pS / np.double(Nbins)
sample_p = np.array(range(self.pS))
sample_ph, sample_pw = np.meshgrid(sample_p,sample_p)
sample_ph.resize(sample_ph.size)
sample_pw.resize(sample_pw.size)
bincenter = np.array(range(1,Nbins*2,2)) / 2.0 / Nbins * self.pS - 0.5
bincenter_h, bincenter_w = np.meshgrid(bincenter,bincenter)
bincenter_h.resize((bincenter_h.size,1))
bincenter_w.resize((bincenter_w.size,1))
dist_ph = abs(sample_ph - bincenter_h)
dist_pw = abs(sample_pw - bincenter_w)
weights_h = dist_ph / sample_res
weights_w = dist_pw / sample_res
weights_h = (1-weights_h) * (weights_h <= 1)
weights_w = (1-weights_w) * (weights_w <= 1)
# weights is the contribution of each pixel to the corresponding bin center
self.weights = weights_h * weights_w
#pyplot.imshow(self.weights)
#pyplot.show()
def process_image(self, image, positionNormalize = True,\
verbose = True):
'''
processes a single image, return the locations
and the values of detected SIFT features.
image: a M*N image which is a numpy 2D array. If you
pass a color image, it will automatically be converted
to a grayscale image.
positionNormalize: whether to normalize the positions
to [0,1]. If False, the pixel-based positions of the
top-right position of the patches is returned.
Return values:
feaArr: the feature array, each row is a feature
positions: the positions of the features
'''
image = image.astype(np.double)
if image.ndim == 3:
# we do not deal with color images.
image = np.mean(image,axis=2)
# compute the grids
H,W = image.shape
gS = self.gS
pS = self.pS
remH = np.mod(H-pS, gS)
remW = np.mod(W-pS, gS)
offsetH = remH/2
offsetW = remW/2
gridH,gridW = np.meshgrid(range(offsetH,H-pS+1,gS), range(offsetW,W-pS+1,gS))
gridH = gridH.flatten()
gridW = gridW.flatten()
if verbose:
print 'Image: w {}, h {}, gs {}, ps {}, nFea {}'.\
format(W,H,gS,pS,gridH.size)
feaArr = self.calculate_sift_grid(image,gridH,gridW)
feaArr = self.normalize_sift(feaArr)
if positionNormalize:
positions = np.vstack((gridH / np.double(H), gridW / np.double(W)))
else:
positions = np.vstack((gridH, gridW))
return feaArr, positions
def calculate_sift_grid(self,image,gridH,gridW):
'''
This function calculates the unnormalized sift features
It is called by process_image().
'''
H,W = image.shape
Npatches = gridH.size
feaArr = np.zeros((Npatches,Nsamples*Nangles))
# calculate gradient
GH,GW = gen_dgauss(self.sigma)
IH = signal.convolve2d(image,GH,mode='same')
IW = signal.convolve2d(image,GW,mode='same')
Imag = np.sqrt(IH**2+IW**2)
Itheta = np.arctan2(IH,IW)
Iorient = np.zeros((Nangles,H,W))
for i in range(Nangles):
Iorient[i] = Imag * np.maximum(np.cos(Itheta - angles[i])**alpha,0)
#pyplot.imshow(Iorient[i])
#pyplot.show()
for i in range(Npatches):
currFeature = np.zeros((Nangles,Nsamples))
for j in range(Nangles):
currFeature[j] = np.dot(self.weights,\
Iorient[j,gridH[i]:gridH[i]+self.pS, gridW[i]:gridW[i]+self.pS].flatten())
feaArr[i] = currFeature.flatten()
return feaArr
def normalize_sift(self,feaArr):
'''
This function does sift feature normalization
following David Lowe's definition (normalize length ->
thresholding at 0.2 -> renormalize length)
'''
siftlen = np.sqrt(np.sum(feaArr**2,axis=1))
hcontrast = (siftlen >= self.nrml_thres)
siftlen[siftlen < self.nrml_thres] = self.nrml_thres
# normalize with contrast thresholding
feaArr /= siftlen.reshape((siftlen.size,1))
# suppress large gradients
feaArr[feaArr>self.sift_thres] = self.sift_thres
# renormalize high-contrast ones
feaArr[hcontrast] /= np.sqrt(np.sum(feaArr[hcontrast]**2,axis=1)).\
reshape((feaArr[hcontrast].shape[0],1))
return feaArr
class SingleSiftExtractor(DsiftExtractor):
'''
The simple wrapper class that does feature extraction, treating
the whole image as a local image patch.
'''
def __init__(self, patchSize,
nrml_thres = 1.0,\
sigma_edge = 0.8,\
sift_thres = 0.2):
# simply call the super class __init__ with a large gridSpace
DsiftExtractor.__init__(self, patchSize, patchSize, nrml_thres, sigma_edge, sift_thres)
def process_image(self, image):
return DsiftExtractor.process_image(self, image, False, False)[0]
if __name__ == '__main__':
# ignore this. I only use this for testing purpose...
from scipy import misc
extractor = DsiftExtractor(8,16,1)
image = misc.imread('lena.png')
image = np.mean(np.double(image),axis=2)
feaArr,positions = extractor.process_image(image)
#pyplot.hist(feaArr.flatten(),bins=100)
#pyplot.imshow(feaArr[:256])
#pyplot.plot(np.sum(feaArr,axis=0))
pyplot.imshow(feaArr[np.random.permutation(feaArr.shape[0])[:256]])
# test single sift extractor
extractor = SingleSiftExtractor(16)
feaArrSingle = extractor.process_image(image[:16,:16])
pyplot.figure()
pyplot.plot(feaArr[0],'r')
pyplot.plot(feaArrSingle,'b')
pyplot.show()