-
Notifications
You must be signed in to change notification settings - Fork 7
/
SegmentEditorEffect.py
308 lines (254 loc) · 12.2 KB
/
SegmentEditorEffect.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
import gc
import os.path
from SegmentEditorEffects import *
import monai
from monai.inferers.utils import sliding_window_inference
from monai.networks.layers import Norm
from monai.networks.nets.unet import UNet
from monai.transforms import (AddChanneld, Compose, Orientationd, ScaleIntensityRanged, Spacingd, ToTensord, Resized,
Resize, CropForegroundd, ScaleIntensityRange)
from monai.transforms.compose import MapTransform
from monai.transforms.post.array import AsDiscrete, KeepLargestConnectedComponent
import numpy as np
import qt
import slicer
from slicer.ScriptedLoadableModule import *
import slicer.modules
from slicer.util import VTKObservationMixin
import torch
import vtk
class SegmentEditorEffect(AbstractScriptedSegmentEditorEffect):
"""This effect segments the liver in the input volume using a UNet model"""
def __init__(self, scriptedEffect):
self.device = qt.QComboBox()
self.modality = qt.QComboBox()
scriptedEffect.name = 'Segment CT/MRI Liver'
scriptedEffect.perSegment = True # this effect operates on a single selected segment
AbstractScriptedSegmentEditorEffect.__init__(self, scriptedEffect)
self.logic = SegmentEditorEffectLogic()
self.clippedMasterImageData = None
self.lastRoiNodeId = ""
self.lastRoiNodeModifiedTime = 0
self.roiSelector = slicer.qMRMLNodeComboBox()
def clone(self):
# It should not be necessary to modify this method
import qSlicerSegmentationsEditorEffectsPythonQt as effects
clonedEffect = effects.qSlicerSegmentEditorScriptedEffect(None)
clonedEffect.setPythonSource(__file__.replace('\\', '/'))
return clonedEffect
def icon(self):
# It should not be necessary to modify this method
iconPath = os.path.join(os.path.dirname(__file__), 'SegmentEditorEffect.png')
if os.path.exists(iconPath):
return qt.QIcon(iconPath)
return qt.QIcon()
def helpText(self):
return "<html>Segments the liver using a UNet model in CT/MRI modality Volumes<br><br>" \
"A ROI may be necessary to limit memory consumption.</html>"
def setupOptionsFrame(self):
"""
Setup the ROI selection comboBox and the apply segmentation button
"""
# CPU / CUDA options
self.device.addItems(["cuda", "cpu"])
self.scriptedEffect.addLabeledOptionsWidget("Device:", self.device)
self.modality.addItems(["CT", "MRI"])
self.scriptedEffect.addLabeledOptionsWidget("Modality:", self.modality)
# Add ROI options
self.roiSelector.nodeTypes = ['vtkMRMLMarkupsROINode']
self.roiSelector.noneEnabled = True
self.roiSelector.setMRMLScene(slicer.mrmlScene)
self.scriptedEffect.addLabeledOptionsWidget("ROI: ", self.roiSelector)
# Toggle ROI visibility button
toggleROIVisibilityButton = qt.QPushButton("Toggle ROI Visibility")
toggleROIVisibilityButton.objectName = self.__class__.__name__ + 'ToggleROIVisibility'
toggleROIVisibilityButton.setToolTip("Toggle selected ROI visibility")
toggleROIVisibilityButton.connect('clicked()', self.toggleROIVisibility)
self.scriptedEffect.addOptionsWidget(toggleROIVisibilityButton)
# Apply button
applyButton = qt.QPushButton("Apply")
applyButton.objectName = self.__class__.__name__ + 'Apply'
applyButton.setToolTip("Extract liver from input volume")
applyButton.connect('clicked()', self.onApply)
self.scriptedEffect.addOptionsWidget(applyButton)
def activate(self):
"""
When activated, disable effect in the view and reset the clipped image data.
"""
self.scriptedEffect.showEffectCursorInSliceView = False
self.clippedMasterImageData = None
def onApply(self):
"""
When applied, crop the input volume if necessary and run the UNet segmentation model on the cropped volume.
Overwrites the selected segment labelMap when done.
"""
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
masterVolumeNode = slicer.vtkMRMLScalarVolumeNode()
slicer.mrmlScene.AddNode(masterVolumeNode)
slicer.vtkSlicerSegmentationsModuleLogic.CopyOrientedImageDataToVolumeNode(self.getClippedMasterImageData(),
masterVolumeNode)
try:
self.logic.launchLiverSegmentation(masterVolumeNode, use_cuda=self.device.currentText == "cuda",
modality=self.modality.currentText)
self.scriptedEffect.saveStateForUndo()
self.scriptedEffect.modifySelectedSegmentByLabelmap(
slicer.vtkSlicerSegmentationsModuleLogic.CreateOrientedImageDataFromVolumeNode(masterVolumeNode),
slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet)
except Exception as e:
qt.QApplication.restoreOverrideCursor()
slicer.util.errorDisplay(str(e))
finally:
qt.QApplication.restoreOverrideCursor()
slicer.mrmlScene.RemoveNode(masterVolumeNode)
def getClippedMasterImageData(self):
"""
Crops the master volume node if a ROI Node is selected in the parameter comboBox. Otherwise returns the full extent
of the volume.
"""
# Return masterImageData unchanged if there is no ROI
masterImageData = self.scriptedEffect.masterVolumeImageData()
roiNode = self.roiSelector.currentNode()
if roiNode is None or masterImageData is None:
self.clippedMasterImageData = None
self.lastRoiNodeId = ""
self.lastRoiNodeModifiedTime = 0
return masterImageData
# Return last clipped image data if there was no change
if (
self.clippedMasterImageData is not None and roiNode.GetID() == self.lastRoiNodeId and roiNode.GetMTime() == self.lastRoiNodeModifiedTime):
# Use cached clipped master image data
return self.clippedMasterImageData
# Compute clipped master image
import SegmentEditorLocalThresholdLib
self.clippedMasterImageData = SegmentEditorLocalThresholdLib.SegmentEditorEffect.cropOrientedImage(masterImageData,
roiNode)
self.lastRoiNodeId = roiNode.GetID()
self.lastRoiNodeModifiedTime = roiNode.GetMTime()
return self.clippedMasterImageData
def toggleROIVisibility(self):
"""
Toggles the visibility of the currently selected ROI.
"""
roiNode = self.roiSelector.currentNode()
if roiNode is None:
return
roiNode.SetDisplayVisibility(not roiNode.GetDisplayVisibility())
class Normalized(MapTransform):
"""
Normalizes input
"""
def __init__(self, keys, meta_key_postfix: str = "meta_dict") -> None:
super().__init__(keys)
self.meta_key_postfix = meta_key_postfix
self.keys = keys
def __call__(self, volume_node):
d = dict(volume_node)
for key in self.keys:
d[key] = ScaleIntensityRange(a_max=np.amax(d[key]), a_min=np.amin(d[key]), b_max=1.0, b_min=0.0, clip=True)(
d[key])
return d
class SlicerLoadImage(MapTransform):
"""
Adapter from Slicer VolumeNode to MONAI volumes.
"""
def __init__(self, keys, meta_key_postfix: str = "meta_dict") -> None:
super().__init__(keys)
self.meta_key_postfix = meta_key_postfix
def __call__(self, volume_node):
data = slicer.util.arrayFromVolume(volume_node)
data = np.swapaxes(data, 0, 2)
print("Load volume from Slicer : {}Mb\tshape {}\tdtype {}".format(data.nbytes * 0.000001, data.shape, data.dtype))
spatial_shape = data.shape
# apply spacing
m = vtk.vtkMatrix4x4()
volume_node.GetIJKToRASMatrix(m)
affine = slicer.util.arrayFromVTKMatrix(m)
meta_data = {"affine": affine, "original_affine": affine, "spacial_shape": spatial_shape,
'original_spacing': volume_node.GetSpacing()}
return {self.keys[0]: data, '{}_{}'.format(self.keys[0], self.meta_key_postfix): meta_data}
class SegmentEditorEffectLogic(ScriptedLoadableModuleLogic):
"""
Logic class responsible for instantiating the UNet model and running the segmentation on the input node.
"""
def __init__(self):
ScriptedLoadableModuleLogic.__init__(self)
@classmethod
def createUNetModel(cls, device):
return UNet(dimensions=3, in_channels=1, out_channels=2, channels=(16, 32, 64, 128, 256), strides=(2, 2, 2, 2),
num_res_units=2, norm=Norm.BATCH, ).to(device)
@classmethod
def getPreprocessingTransform(cls, modality):
"""
Preprocessing transform which converts the input volume to MONAI format and resamples and normalizes its inputs.
The values in this transform are the same as in the training transform preprocessing.
"""
if modality == "CT":
trans = [SlicerLoadImage(keys=["image"]), AddChanneld(keys=["image"]),
Spacingd(keys=["image"], pixdim=(1.5, 1.5, 2.0), mode="bilinear"),
Orientationd(keys=["image"], axcodes="RAS"),
ScaleIntensityRanged(keys=["image"], a_min=-57, a_max=164, b_min=0.0, b_max=1.0, clip=True),
AddChanneld(keys=["image"]),
ToTensord(keys=["image"]), ]
return Compose(trans)
elif modality == "MRI":
trans = [SlicerLoadImage(keys=["image"]), AddChanneld(keys=["image"]),
Spacingd(keys=["image"], pixdim=(1.5, 1.5, 2.0), mode="bilinear"),
Orientationd(keys=["image"], axcodes="LPS"),
Normalized(keys=["image"]),
AddChanneld(keys=["image"]),
ToTensord(keys=["image"])]
return Compose(trans)
@classmethod
def getPostProcessingTransform(cls, original_spacing, original_size, modality):
"""
Simple post processing transform to convert the volume back to its original spacing.
"""
return Compose([
AddChanneld(keys=["image"]),
Spacingd(keys=["image"], pixdim=original_spacing, mode="nearest"),
Resized(keys=["image"], spatial_size=original_size)
])
@classmethod
def launchLiverSegmentation(cls, in_out_volume_node, use_cuda, modality):
"""
Runs the segmentation on the input volume and returns the segmentation in the same volume.
"""
device = torch.device("cpu") if not use_cuda or not torch.cuda.is_available() else torch.device("cuda:0")
print("Start liver segmentation using device :", device)
print(f"Using modality {modality}")
try:
with torch.no_grad():
model_path = os.path.join(os.path.dirname(__file__),
"liver_ct_model.pt" if modality == "CT" else "liver_mri_model.pt")
model = cls.createUNetModel(device=device)
model.load_state_dict(torch.load(model_path, map_location=device))
transform_output = cls.getPreprocessingTransform(modality)(in_out_volume_node)
model_input = transform_output["image"].to(device)
print("Run UNet model on input volume")
roi_size = (160, 160, 160) if modality == "CT" else (240, 240, 96)
model_output = sliding_window_inference(model_input, roi_size, 4, model, device="cpu", sw_device=device)
print("Keep largest connected components and threshold UNet output")
discrete_output = AsDiscrete(argmax=True)(model_output.reshape(model_output.shape[-4:]))
post_processed = KeepLargestConnectedComponent(applied_labels=[1])(discrete_output)
output_volume = post_processed.cpu().numpy()[0, :, :, :]
del post_processed, discrete_output, model_output, model, model_input
transform_output["image"] = output_volume
original_spacing = (transform_output["image_meta_dict"]["original_spacing"])
original_size = (transform_output["image_meta_dict"]["spacial_shape"])
output_inverse_transform = cls.getPostProcessingTransform(original_spacing, original_size, modality)(
transform_output)
label_map_input = output_inverse_transform["image"][0, :, :, :]
print("output label map shape is " + str(label_map_input.shape))
output_affine_matrix = transform_output["image_meta_dict"]["affine"]
in_out_volume_node.SetIJKToRASMatrix(slicer.util.vtkMatrixFromArray(output_affine_matrix))
slicer.util.updateVolumeFromArray(in_out_volume_node, np.swapaxes(label_map_input, 0, 2))
del transform_output
finally:
# Cleanup any remaining memory
def del_local(v):
if v in locals():
del locals()[v]
for n in ["model_input", "model_output", "post_processed", "model", "transform_output"]:
del_local(n)
gc.collect()
torch.cuda.empty_cache()