-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvolume_slicer.py
executable file
·327 lines (268 loc) · 11.6 KB
/
volume_slicer.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
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
#!/usr/bin/env python
"""
Quick script to visualize 3D and 4D Nifti with Mayavi.
This script comes with no help whatsoever from the author (seriously)!
Read the Mayavi documentation if you have questions.
"""
# Author: Gael Varoquaux
# License: BSD
import numpy as np
from traits.api import HasTraits, Instance, Array, Int, \
Bool, Dict, on_trait_change, Range, Property, Button
from traitsui.api import View, Item, HGroup, Group
from tvtk.api import tvtk
from tvtk.pyface.scene import Scene
from mayavi import mlab
from mayavi.core.api import PipelineBase, Source
from mayavi.core.ui.api import SceneEditor, MlabSceneModel
################################################################################
# The object implementing the dialog
class VolumeSlicer(HasTraits):
# The data to plot
data = Array
# The position of the view
position = Array(shape=(3,))
# The 4 views displayed
scene3d = Instance(MlabSceneModel, ())
scene_x = Instance(MlabSceneModel, ())
scene_y = Instance(MlabSceneModel, ())
scene_z = Instance(MlabSceneModel, ())
# The data source
data_src = Instance(Source)
# The image plane widgets of the 3D scene
ipw_3d_x = Instance(PipelineBase)
ipw_3d_y = Instance(PipelineBase)
ipw_3d_z = Instance(PipelineBase)
# The cursors on each view:
cursors = Dict()
disable_render = Bool
_axis_names = dict(x=0, y=1, z=2)
#---------------------------------------------------------------------------
# Object interface
#---------------------------------------------------------------------------
def __init__(self, **traits):
super(VolumeSlicer, self).__init__(**traits)
# Force the creation of the image_plane_widgets:
self.ipw_3d_x
self.ipw_3d_y
self.ipw_3d_z
#---------------------------------------------------------------------------
# Default values
#---------------------------------------------------------------------------
def _position_default(self):
return 0.5*np.array(self.data.shape)
def _data_src_default(self):
return mlab.pipeline.scalar_field(self.data,
figure=self.scene3d.mayavi_scene,
name='Data',)
def make_ipw_3d(self, axis_name):
ipw = mlab.pipeline.image_plane_widget(self.data_src,
figure=self.scene3d.mayavi_scene,
plane_orientation='%s_axes' % axis_name,
name='Cut %s' % axis_name)
return ipw
def _ipw_3d_x_default(self):
return self.make_ipw_3d('x')
def _ipw_3d_y_default(self):
return self.make_ipw_3d('y')
def _ipw_3d_z_default(self):
return self.make_ipw_3d('z')
#---------------------------------------------------------------------------
# Scene activation callbacks
#---------------------------------------------------------------------------
@on_trait_change('scene3d.activated')
def display_scene3d(self):
outline = mlab.pipeline.outline(self.data_src,
figure=self.scene3d.mayavi_scene,
)
self.scene3d.mlab.view(40, 50)
# Interaction properties can only be changed after the scene
# has been created, and thus the interactor exists
for ipw in (self.ipw_3d_x, self.ipw_3d_y, self.ipw_3d_z):
ipw.ipw.interaction = 0
self.scene3d.scene.background = (0, 0, 0)
# Keep the view always pointing up
self.scene3d.scene.interactor.interactor_style = \
tvtk.InteractorStyleTerrain()
self.update_position()
def make_side_view(self, axis_name):
scene = getattr(self, 'scene_%s' % axis_name)
scene.scene.parallel_projection = True
ipw_3d = getattr(self, 'ipw_3d_%s' % axis_name)
# We create the image_plane_widgets in the side view using a
# VTK dataset pointing to the data on the corresponding
# image_plane_widget in the 3D view (it is returned by
# ipw_3d._get_reslice_output())
side_src = ipw_3d.ipw._get_reslice_output()
ipw = mlab.pipeline.image_plane_widget(
side_src,
plane_orientation='z_axes',
vmin=self.data.min(),
vmax=self.data.max(),
figure=scene.mayavi_scene,
name='Cut view %s' % axis_name,
)
setattr(self, 'ipw_%s' % axis_name, ipw)
# Extract the spacing of the side_src to convert coordinates
# into indices
spacing = side_src.spacing
# Make left-clicking create a crosshair
ipw.ipw.left_button_action = 0
x, y, z = self.position
cursor = mlab.points3d(x, y, z,
mode='axes',
color=(0, 0, 0),
scale_factor=2*max(self.data.shape),
figure=scene.mayavi_scene,
name='Cursor view %s' % axis_name,
)
self.cursors[axis_name] = cursor
# Add a callback on the image plane widget interaction to
# move the others
this_axis_number = self._axis_names[axis_name]
def move_view(obj, evt):
# Disable rendering on all scene
position = list(obj.GetCurrentCursorPosition()*spacing)[:2]
position.insert(this_axis_number, self.position[this_axis_number])
# We need to special case y, as the view has been rotated.
if axis_name is 'y':
position = position[::-1]
self.position = position
ipw.ipw.add_observer('InteractionEvent', move_view)
ipw.ipw.add_observer('StartInteractionEvent', move_view)
# Center the image plane widget
ipw.ipw.slice_position = 0.5*self.data.shape[
self._axis_names[axis_name]]
# 2D interaction: only pan and zoom
scene.scene.interactor.interactor_style = \
tvtk.InteractorStyleImage()
scene.scene.background = (0, 0, 0)
# Some text:
mlab.text(0.01, 0.8, axis_name, width=0.08)
# Choose a view that makes sens
views = dict(x=(0, 0), y=(90, 180), z=(0, 0))
mlab.view(views[axis_name][0],
views[axis_name][1],
focalpoint=0.5*np.array(self.data.shape),
figure=scene.mayavi_scene)
scene.scene.camera.parallel_scale = 0.52*np.mean(self.data.shape)
@on_trait_change('scene_x.activated')
def display_scene_x(self):
return self.make_side_view('x')
@on_trait_change('scene_y.activated')
def display_scene_y(self):
return self.make_side_view('y')
@on_trait_change('scene_z.activated')
def display_scene_z(self):
return self.make_side_view('z')
#---------------------------------------------------------------------------
# Traits callback
#---------------------------------------------------------------------------
@on_trait_change('position')
def update_position(self):
""" Update the position of the cursors on each side view, as well
as the image_plane_widgets in the 3D view.
"""
# First disable rendering in all scenes to avoid unecessary
# renderings
self.disable_render = True
# For each axis, move image_plane_widget and the cursor in the
# side view
for axis_name, axis_number in self._axis_names.iteritems():
ipw3d = getattr(self, 'ipw_3d_%s' % axis_name)
ipw3d.ipw.slice_position = self.position[axis_number]
# Go from the 3D position, to the 2D coordinates in the
# side view
position2d = list(self.position)
position2d.pop(axis_number)
if axis_name is 'y':
position2d = position2d[::-1]
# Move the cursor
# For the following to work, you need Mayavi 3.4.0, if you
# have a less recent version, use 'x=[position2d[0]]'
self.cursors[axis_name].mlab_source.set(
x=position2d[0],
y=position2d[1],
z=0)
# Finally re-enable rendering
self.disable_render = False
@on_trait_change('disable_render')
def _render_enable(self):
for scene in (self.scene3d, self.scene_x, self.scene_y,
self.scene_z):
scene.scene.disable_render = self.disable_render
@on_trait_change('data')
def _redraw(self):
self.data_src.mlab_source.scalars = self.data
#---------------------------------------------------------------------------
# The layout of the dialog created
#---------------------------------------------------------------------------
view = View(HGroup(
Group(
Item('scene_y',
editor=SceneEditor(scene_class=Scene),
height=250, width=300),
Item('scene_z',
editor=SceneEditor(scene_class=Scene),
height=250, width=300),
show_labels=False,
),
Group(
Item('scene_x',
editor=SceneEditor(scene_class=Scene),
height=250, width=300),
Item('scene3d',
editor=SceneEditor(scene_class=Scene),
height=250, width=300),
show_labels=False,
),
),
resizable=True,
title='Volume Slicer',
)
class MultiVolumeSlicer(HasTraits):
# For 4D data
volume_slicer = Instance(VolumeSlicer)
vol_nb = Range(value=0, low='_zero',
high='_volume_max', mode='spinner',
help="Number of the volume to display",
)
data = Array
mayavi_dialog = Button('Show pipeline')
# A stupid traits to get the range happy.
_zero = Int(0)
_volume_max = Property(depends_on="data")
def _mayavi_dialog_fired(self):
mlab.show_pipeline()
def _get__volume_max(self):
return self.data.shape[-1] - 1
def __init__(self, **traits):
super(MultiVolumeSlicer, self).__init__(**traits)
# Force the setting of the volume_slicer
self.volume_slicer = VolumeSlicer(data=self.data[..., 0])
@on_trait_change('data,vol_nb')
def compute_3d(self):
"Compute the 3D volume from the 4D data"
if self.volume_slicer is not None:
self.volume_slicer.data = self.data[..., self.vol_nb]
view = View(Group(
HGroup('vol_nb', 'mayavi_dialog'),
HGroup(Item('volume_slicer', style='custom'),
show_labels=False),
),
resizable=True,
title='Volume Slicer',
)
################################################################################
if __name__ == '__main__':
# Create some data
import nibabel
import sys
filename = sys.argv[1]
img = nibabel.load(filename)
data = img.get_data()
if len(data.shape) == 3:
m = VolumeSlicer(data=data)
else:
m = MultiVolumeSlicer(data=data)
m.configure_traits()