forked from pmneila/morphsnakes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples.py
277 lines (204 loc) · 8.11 KB
/
examples.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
import os
import logging
import numpy as np
from imageio import imread
import matplotlib
from matplotlib import pyplot as plt
import morphsnakes as ms
# in case you are running on machine without display, e.g. server
if os.environ.get('DISPLAY', '') == '':
logging.warning('No display found. Using non-interactive Agg backend.')
matplotlib.use('Agg')
PATH_IMG_NODULE = 'images/mama07ORI.bmp'
PATH_IMG_STARFISH = 'images/seastar2.png'
PATH_IMG_LAKES = 'images/lakes3.jpg'
PATH_IMG_CAMERA = 'images/camera.png'
PATH_IMG_COINS = 'images/coins.png'
PATH_ARRAY_CONFOCAL = 'images/confocal.npy'
def visual_callback_2d(background, fig=None):
"""
Returns a callback than can be passed as the argument `iter_callback`
of `morphological_geodesic_active_contour` and
`morphological_chan_vese` for visualizing the evolution
of the levelsets. Only works for 2D images.
Parameters
----------
background : (M, N) array
Image to be plotted as the background of the visual evolution.
fig : matplotlib.figure.Figure
Figure where results will be drawn. If not given, a new figure
will be created.
Returns
-------
callback : Python function
A function that receives a levelset and updates the current plot
accordingly. This can be passed as the `iter_callback` argument of
`morphological_geodesic_active_contour` and
`morphological_chan_vese`.
"""
# Prepare the visual environment.
if fig is None:
fig = plt.figure()
fig.clf()
ax1 = fig.add_subplot(1, 2, 1)
ax1.imshow(background, cmap=plt.cm.gray)
ax2 = fig.add_subplot(1, 2, 2)
ax_u = ax2.imshow(np.zeros_like(background), vmin=0, vmax=1)
plt.pause(0.001)
def callback(levelset):
if ax1.collections:
del ax1.collections[0]
ax1.contour(levelset, [0.5], colors='r')
ax_u.set_data(levelset)
fig.canvas.draw()
plt.pause(0.001)
return callback
def visual_callback_3d(fig=None, plot_each=1):
"""
Returns a callback than can be passed as the argument `iter_callback`
of `morphological_geodesic_active_contour` and
`morphological_chan_vese` for visualizing the evolution
of the levelsets. Only works for 3D images.
Parameters
----------
fig : matplotlib.figure.Figure
Figure where results will be drawn. If not given, a new figure
will be created.
plot_each : positive integer
The plot will be updated once every `plot_each` calls to the callback
function.
Returns
-------
callback : Python function
A function that receives a levelset and updates the current plot
accordingly. This can be passed as the `iter_callback` argument of
`morphological_geodesic_active_contour` and
`morphological_chan_vese`.
"""
from mpl_toolkits.mplot3d import Axes3D
# PyMCubes package is required for `visual_callback_3d`
try:
import mcubes
except ImportError:
raise ImportError("PyMCubes is required for 3D `visual_callback_3d`")
# Prepare the visual environment.
if fig is None:
fig = plt.figure()
fig.clf()
ax = fig.add_subplot(111, projection='3d')
plt.pause(0.001)
counter = [-1]
def callback(levelset):
counter[0] += 1
if (counter[0] % plot_each) != 0:
return
if ax.collections:
del ax.collections[0]
coords, triangles = mcubes.marching_cubes(levelset, 0.5)
ax.plot_trisurf(coords[:, 0], coords[:, 1], coords[:, 2],
triangles=triangles)
plt.pause(0.1)
return callback
def rgb2gray(img):
"""Convert a RGB image to gray scale."""
return 0.2989 * img[..., 0] + 0.587 * img[..., 1] + 0.114 * img[..., 2]
def example_nodule():
logging.info('Running: example_nodule (MorphGAC)...')
# Load the image.
img = imread(PATH_IMG_NODULE)[..., 0] / 255.0
# g(I)
gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=5.48)
# Initialization of the level-set.
init_ls = ms.circle_level_set(img.shape, (100, 126), 20)
# Callback for visual plotting
callback = visual_callback_2d(img)
# MorphGAC.
ms.morphological_geodesic_active_contour(gimg, iterations=45,
init_level_set=init_ls,
smoothing=1, threshold=0.31,
balloon=1, iter_callback=callback)
def example_starfish():
logging.info('Running: example_starfish (MorphGAC)...')
# Load the image.
imgcolor = imread(PATH_IMG_STARFISH) / 255.0
img = rgb2gray(imgcolor)
# g(I)
gimg = ms.inverse_gaussian_gradient(img, alpha=1000, sigma=2)
# Initialization of the level-set.
init_ls = ms.circle_level_set(img.shape, (163, 137), 135)
# Callback for visual plotting
callback = visual_callback_2d(imgcolor)
# MorphGAC.
ms.morphological_geodesic_active_contour(gimg, iterations=100,
init_level_set=init_ls,
smoothing=2, threshold=0.3,
balloon=-1, iter_callback=callback)
def example_coins():
logging.info('Running: example_coins (MorphGAC)...')
# Load the image.
img = imread(PATH_IMG_COINS) / 255.0
# g(I)
gimg = ms.inverse_gaussian_gradient(img)
# Manual initialization of the level set
init_ls = np.zeros(img.shape, dtype=np.int8)
init_ls[10:-10, 10:-10] = 1
# Callback for visual plotting
callback = visual_callback_2d(img)
# MorphGAC.
ms.morphological_geodesic_active_contour(gimg, 230, init_ls,
smoothing=1, threshold=0.69,
balloon=-1, iter_callback=callback)
def example_lakes():
logging.info('Running: example_lakes (MorphACWE)...')
# Load the image.
imgcolor = imread(PATH_IMG_LAKES)/255.0
img = rgb2gray(imgcolor)
# MorphACWE does not need g(I)
# Initialization of the level-set.
init_ls = ms.circle_level_set(img.shape, (80, 170), 25)
# Callback for visual plotting
callback = visual_callback_2d(imgcolor)
# Morphological Chan-Vese (or ACWE)
ms.morphological_chan_vese(img, iterations=200,
init_level_set=init_ls,
smoothing=3, lambda1=1, lambda2=1,
iter_callback=callback)
def example_camera():
"""
Example with `morphological_chan_vese` with using the default
initialization of the level-set.
"""
logging.info('Running: example_camera (MorphACWE)...')
# Load the image.
img = imread(PATH_IMG_CAMERA)/255.0
# Callback for visual plotting
callback = visual_callback_2d(img)
# Morphological Chan-Vese (or ACWE)
ms.morphological_chan_vese(img, 35,
smoothing=3, lambda1=1, lambda2=1,
iter_callback=callback)
def example_confocal3d():
logging.info('Running: example_confocal3d (MorphACWE)...')
# Load the image.
img = np.load(PATH_ARRAY_CONFOCAL)
# Initialization of the level-set.
init_ls = ms.circle_level_set(img.shape, (30, 50, 80), 25)
# Callback for visual plotting
callback = visual_callback_3d(plot_each=20)
# Morphological Chan-Vese (or ACWE)
ms.morphological_chan_vese(img, iterations=150,
init_level_set=init_ls,
smoothing=1, lambda1=1, lambda2=2,
iter_callback=callback)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
example_nodule()
example_starfish()
example_coins()
example_lakes()
example_camera()
# Uncomment the following line to see a 3D example
# This is skipped by default since mplot3d is VERY slow plotting 3d meshes
# example_confocal3d()
logging.info("Done.")
plt.show()