Newer
Older
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Anders Bjorholm Dahl
abda@dtu.dk
"""
import numpy as np
import matplotlib.pyplot as plt
import skimage.io
import skimage.feature
import cv2
#%% Computing Gaussian and its second order derivative
data_path = '../../../../Data/week2/' # replace with your own data path
im = skimage.io.imread(data_path + 'test_blob_uniform.png').astype(np.float)
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im,cmap='gray')
def getGaussDerivative(t):
'''
Computes kernels of Gaussian and its derivatives.
Parameters
----------
t : float
Vairance - t.
Returns
-------
g : numpy array
Gaussian.
dg : numpy array
First order derivative of Gaussian.
ddg : numpy array
Second order derivative of Gaussian
dddg : numpy array
Third order derivative of Gaussian.
'''
kSize = 5
s = np.sqrt(t)
x = np.arange(int(-np.ceil(s*kSize)), int(np.ceil(s*kSize))+1)
x = np.reshape(x,(-1,1))
g = np.exp(-x**2/(2*t))
g = g/np.sum(g)
dg = -x/t*g
ddg = -g/t - x/t*dg
dddg = -2*dg/t - x/t*ddg
return g, dg, ddg, dddg
g, dg, ddg, dddg = getGaussDerivative(3)
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.plot(g)
ax.plot(dg)
ax.plot(ddg)
ax.plot(dddg)
#%% Convolve an image
t = 325
g, dg, ddg, dddg = getGaussDerivative(t)
Lg = cv2.filter2D(cv2.filter2D(im, -1, g), -1, g.T)
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(Lg,cmap='gray')
#%% Detecting blobs on one scale
im = skimage.io.imread(data_path + 'test_blob_uniform.png').astype(np.float)
Lxx = cv2.filter2D(cv2.filter2D(im, -1, g), -1, ddg.T)
Lyy = cv2.filter2D(cv2.filter2D(im, -1, ddg), -1, g.T)
L_blob = t*(Lxx + Lyy)
# how blob response
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
pos = ax.imshow(L_blob, cmap='gray')
fig.colorbar(pos)
#%% Find regional maximum in Laplacian
magnitudeThres = 50
coord_pos = skimage.feature.peak_local_max(L_blob, threshold_abs=magnitudeThres)
coord_neg = skimage.feature.peak_local_max(-L_blob, threshold_abs=magnitudeThres)
coord = np.r_[coord_pos, coord_neg]
# Show circles
theta = np.arange(0, 2*np.pi, step=np.pi/100)
theta = np.append(theta, 0)
circ = np.array((np.cos(theta),np.sin(theta)))
n = coord.shape[0]
m = circ.shape[1]
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
plt.plot(coord[:,1], coord[:,0], '.r')
circ_y = np.sqrt(2*t)*np.reshape(circ[0,:],(1,-1)).T*np.ones((1,n)) + np.ones((m,1))*np.reshape(coord[:,0],(-1,1)).T
circ_x = np.sqrt(2*t)*np.reshape(circ[1,:],(1,-1)).T*np.ones((1,n)) + np.ones((m,1))*np.reshape(coord[:,1],(-1,1)).T
plt.plot(circ_x, circ_y, 'r')
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Detecting blobs on multiple scales
im = skimage.io.imread(data_path + 'test_blob_varying.png').astype(np.float)
t = 15
g, dg, ddg, dddg = getGaussDerivative(t)
r,c = im.shape
n = 100
L_blob_vol = np.zeros((r,c,n))
tStep = np.zeros(n)
Lg = im
for i in range(0,n):
tStep[i] = t*i
L_blob_vol[:,:,i] = t*i*(cv2.filter2D(cv2.filter2D(Lg, -1, g), -1, ddg.T) +
cv2.filter2D(cv2.filter2D(Lg, -1, ddg), -1, g.T))
Lg = cv2.filter2D(cv2.filter2D(Lg, -1, g), -1, g.T)
#%% find maxima in scale-space
thres = 40.0
coord_pos = skimage.feature.peak_local_max(L_blob_vol, threshold_abs = thres)
coord_neg = skimage.feature.peak_local_max(-L_blob_vol, threshold_abs = thres)
coord = np.r_[coord_pos,coord_neg]
# Show circles
theta = np.arange(0, 2*np.pi, step=np.pi/100)
theta = np.append(theta, 0)
circ = np.array((np.cos(theta),np.sin(theta)))
n = coord.shape[0]
m = circ.shape[1]
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
plt.plot(coord[:,1], coord[:,0], '.r')
scale = tStep[coord[:,2]]
circ_y = np.sqrt(2*scale)*np.reshape(circ[0,:],(1,-1)).T*np.ones((1,n)) + np.ones((m,1))*np.reshape(coord[:,0],(-1,1)).T
circ_x = np.sqrt(2*scale)*np.reshape(circ[1,:],(1,-1)).T*np.ones((1,n)) + np.ones((m,1))*np.reshape(coord[:,1],(-1,1)).T
plt.plot(circ_x, circ_y, 'r')
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Detecting blobs in real data (scale space)
# diameter interval and steps
d = np.arange(10, 24.5, step = 0.4)
tStep = np.sqrt(0.5)*((d/2)**2) # convert to scale
# read image and take out a small part
im = skimage.io.imread(data_path + 'SEM.png').astype(np.float)
im = im[200:500,200:500]
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
#%% Compute scale space
r,c = im.shape
n = d.shape[0]
L_blob_vol = np.zeros((r,c,n))
for i in range(0,n):
g, dg, ddg, dddg = getGaussDerivative(tStep[i])
L_blob_vol[:,:,i] = tStep[i]*(cv2.filter2D(cv2.filter2D(im,-1,g),-1,ddg.T) +
cv2.filter2D(cv2.filter2D(im,-1,ddg),-1,g.T))
#%% Find maxima in scale space
thres = 30
coord = skimage.feature.peak_local_max(-L_blob_vol, threshold_abs = thres)
# Show circles
def getCircles(coord, scale):
'''
Comptue circle coordinages
Parameters
----------
coord : numpy array
2D array of coordinates.
scale : numpy array
scale of individual blob (t).
Returns
-------
circ_x : numpy array
x coordinates of circle. Each column is one circle.
circ_y : numpy array
y coordinates of circle. Each column is one circle.
'''
theta = np.arange(0, 2*np.pi, step=np.pi/100)
theta = np.append(theta, 0)
circ = np.array((np.cos(theta),np.sin(theta)))
n = coord.shape[0]
m = circ.shape[1]
circ_y = np.sqrt(2*scale)*circ[[0],:].T*np.ones((1,n)) + np.ones((m,1))*coord[:,[0]].T
circ_x = np.sqrt(2*scale)*circ[[1],:].T*np.ones((1,n)) + np.ones((m,1))*coord[:,[1]].T
return circ_x, circ_y
scale = tStep[coord[:,2]]
circ_x, circ_y = getCircles(coord[:,0:2], scale)
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
plt.plot(coord[:,1], coord[:,0], '.r')
plt.plot(circ_x, circ_y, 'r')
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Localize blobs - Example high resolution lab X-ray CT - find the coordinates
# using Gaussian smoothing and use the scale space to find the scale
im = skimage.io.imread(data_path + 'CT_lab_high_res.png').astype(np.float)/255
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
# %% Set parameters
def detectFibers(im, diameterLimit, stepSize, tCenter, thresMagnitude):
'''
Detects fibers in images by finding maxima of Gaussian smoothed image
Parameters
----------
im : numpy array
Image.
diameterLimit : numpy array
2 x 1 vector of limits of diameters of the fibers (in pixels).
stepSize : float
step size in pixels.
tCenter : float
Scale of the Gaussian for center detection.
thresMagnitude : float
Threshold on blob magnitude.
Returns
-------
coord : numpy array
n x 2 array of coordinates with row and column coordinates in each column.
scale : numpy array
n x 1 array of scales t (variance of the Gaussian).
'''
radiusLimit = diameterLimit/2
radiusSteps = np.arange(radiusLimit[0], radiusLimit[1]+0.1, stepSize)
tStep = radiusSteps**2/np.sqrt(2)
r,c = im.shape
n = tStep.shape[0]
L_blob_vol = np.zeros((r,c,n))
for i in range(0,n):
g, dg, ddg, dddg = getGaussDerivative(tStep[i])
L_blob_vol[:,:,i] = tStep[i]*(cv2.filter2D(cv2.filter2D(im,-1,g),-1,ddg.T) +
cv2.filter2D(cv2.filter2D(im,-1,ddg),-1,g.T))
# Detect fibre centers
g, dg, ddg, dddg = getGaussDerivative(tCenter)
Lg = cv2.filter2D(cv2.filter2D(im, -1, g), -1, g.T)
coord = skimage.feature.peak_local_max(Lg, threshold_abs = thresMagnitude)
# Find coordinates and size (scale) of fibres
magnitudeIm = np.min(L_blob_vol, axis = 2)
scaleIm = np.argmin(L_blob_vol, axis = 2)
scales = scaleIm[coord[:,0], coord[:,1]]
magnitudes = -magnitudeIm[coord[:,0], coord[:,1]]
idx = np.where(magnitudes > thresMagnitude)
coord = coord[idx[0],:]
scale = tStep[scales[idx[0]]]
return coord, scale
#%% Set parameters
# Radius limit
diameterLimit = np.array([10,25])
stepSize = 0.3
# Parameter for Gaussian to detect center point
tCenter = 20
# Parameter for finding maxima over Laplacian in scale-space
thresMagnitude = 8
# Detect fibres
coord, scale = detectFibers(im, diameterLimit, stepSize, tCenter, thresMagnitude)
# Plot detected fibres
fig, ax = plt.subplots(1,1,figsize=(10,10),sharex=True,sharey=True)
ax.imshow(im, cmap='gray')
ax.plot(coord[:,1], coord[:,0], 'r.')
circ_x, circ_y = getCircles(coord, scale)
plt.plot(circ_x, circ_y, 'r')