/
LungCTSegmenter.py
2888 lines (2435 loc) · 151 KB
/
LungCTSegmenter.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import time
import glob
import unittest
import logging
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
import SimpleITK as sitk
import sitkUtils
#
# LungCTSegmenter
#
class LungCTSegmenter(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "Lung CT Segmenter"
self.parent.categories = ["Chest Imaging Platform"]
self.parent.dependencies = []
self.parent.contributors = ["Rudolf Bumm (KSGR), Andras Lasso (PERK)"]
self.parent.helpText = """
This module segments lungs and airways from chest CT either with a few user-defined landmarks or by involving AI.
See more information in <a href="https://github.com/rbumm/SlicerLungCTAnalyzer">LungCTAnalyzer extension documentation</a>.<br>
"""
self.parent.acknowledgementText = """
This extension was originally developed by Rudolf Bumm (KSKR) and Andras Lasso (PERK).
<br><br>
AI segmentation involves
<br><br>
<a href="https://github.com/JoHof/lungmask">Lungmask U-net</a><br>See Hofmanninger, J., Prayer, F., Pan, J. et al. Automatic lung segmentation in routine imaging is primarily a data diversity problem, not a methodology problem. Eur Radiol Exp 4, 50 (2020).
<a href="https://doi.org/10.1186/s41747-020-00173-2">https://doi.org/10.1186/s41747-020-00173-2</a>
<br><br>
and<br>
<br>
<a href="https://github.com/wasserth/TotalSegmentator">Totalsegmentator</a><br>See Wasserthal J., Meyer M., , Hanns-Christian Breit H.C., Cyriac J., Shan Y., Segeroth, M.: TotalSegmentator: robust segmentation of 104 anatomical structures in CT images.
<a href="https://arxiv.org/abs/2208.05868">https://arxiv.org/abs/2208.05868</a>
"""
# Sample data is already registered by LungCTAnalyzer module, so there is no need to add here
#
# LungCTSegmenterWidget
#
class LungCTSegmenterWidget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent=None):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.__init__(self, parent)
VTKObservationMixin.__init__(self) # needed for parameter node observation
self.logic = None
self._parameterNode = None
self._rightLungFiducials = None
self._leftLungFiducials = None
self._tracheaFiducials = None
self._updatingGUIFromParameterNode = False
self.createDetailedAirways = False
self.createVessels = False
self.useAI = False
self.fastOption = False
self.shrinkMasks = False
self.detailedMasks = False
self.smoothLungs = True
self.isSufficientNumberOfPointsPlaced = False
self.saveFiducials = False
self.inputVolume = None
self.VolumeRenderingShift = 0
self.volumeRenderingDisplayNode = None
# for testing
#self.batchProcessingInputDir = "D:/Data/OpenSourceCOVIDData/"
#self.batchProcessingOutputDir = "D:/Data/OpenSourceCOVIDData/Segmented"
self.batchProcessingInputDir = ""
self.batchProcessingOutputDir = ""
self.batchProcessingTestMode = False
self.isNiiGzFormat = False
self.batchProcessingIsCancelled = False
self.calibrateData = False
self.lungThresholdMin = 0.
self.lungThresholdMax = 0.
self.airwayThresholdMin = 0.
self.airwayThresholdMax = 0.
self.vesselThresholdMin = 0.
self.vesselThresholdMax = 0.
class checkboxDetails:
def __init__(self, checkbox_name, uiID):
self.name = checkbox_name
self.id = uiID
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath('UI/LungCTSegmenter.ui'))
self.layout.addWidget(uiWidget)
self.layout.objectName = "Lung CT Segmenter layout"
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
# "setMRMLScene(vtkMRMLScene*)" slot.
uiWidget.setMRMLScene(slicer.mrmlScene)
# Create logic class. Logic implements all computations that should be possible to run
# in batch mode, without a graphical user interface.
self.logic = LungCTSegmenterLogic()
self.outputCheckBoxesDict = {
"airways": self.ui.toggleAirwaysCheckBox,
"ribs right": self.ui.toggleRibsRightCheckBox,
"ribs left": self.ui.toggleRibsLeftCheckBox,
"right lung":self.ui.toggleLungRightCheckBox,
"right upper lobe": self.ui.toggleUpperLobeRightCheckBox,
"right middle lobe": self.ui.toggleMiddleLobeRightCheckBox,
"right lower lobe": self.ui.toggleLowerLobeRightCheckBox,
"left lung": self.ui.toggleLungLeftCheckBox,
"left upper lobe": self.ui.toggleUpperLobeLeftCheckBox,
"left lower lobe": self.ui.toggleLowerLobeLeftCheckBox,
"vesselmask": self.ui.toggleVesselMaskCheckBox,
"PA": self.ui.togglePACheckBox,
"PV": self.ui.togglePVCheckBox,
"tumor": self.ui.toggleTumorCheckBox
}
for placeWidget in [self.ui.rightLungPlaceWidget, self.ui.leftLungPlaceWidget, self.ui.tracheaPlaceWidget]:
placeWidget.buttonsVisible=False
placeWidget.placeButton().show()
placeWidget.deleteButton().show()
# Populate comboboxes
list = ["low detail", "medium detail", "high detail"]
self.ui.detailLevelComboBox.addItems(list);
list = [
"lungmask R231",
"lungmask LTRCLobes",
"lungmask LTRCLobes_R231",
"lungmask R231CovidWeb",
"MONAILabel",
"TotalSegmentator lung basic",
"TotalSegmentator lung extended",
]
self.ui.engineAIComboBox.addItems(list);
# Connections
# These connections ensure that we update parameter node when scene is closed
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)
# These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene
# (in the selected parameter node).
self.ui.inputVolumeSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI)
# Connect threshold range sliders
self.ui.LungThresholdRangeWidget.connect('valuesChanged(double,double)', self.onLungThresholdRangeWidgetChanged)
self.ui.AirwayThresholdRangeWidget.connect('valuesChanged(double,double)', self.onAirwayThresholdRangeWidgetChanged)
self.ui.VesselThresholdRangeWidget.connect('valuesChanged(double,double)', self.onVesselThresholdRangeWidgetChanged)
# Connect double sliders
self.ui.VolumeRenderingShiftSliderWidget.connect('valueChanged(double)', self.onShiftSliderWidgetChanged)
# Connect combo boxes
self.ui.detailLevelComboBox.currentTextChanged.connect(self.updateParameterNodeFromGUI)
self.ui.engineAIComboBox.currentTextChanged.connect(self.updateParameterNodeFromGUI)
# Connect check boxes
self.ui.detailedAirwaysCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.createVesselsCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.useAICheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.shrinkMasksCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.detailedMasksCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.saveFiducialsCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.fastCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.smoothLungsCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.testModeCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.niigzFormatCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
self.ui.calibrateDataCheckBox.connect('toggled(bool)', self.updateParameterNodeFromGUI)
for key, uiid in self.outputCheckBoxesDict.items():
uiid.enabled = False
uiid.connect('toggled(bool)', self.updateParameterNodeFromGUI)
# Connect path selectors
self.ui.inputDirectoryPathLineEdit.connect('currentPathChanged(const QString&)', self.onInputDirectoryPathLineEditChanged)
self.ui.outputDirectoryPathLineEdit.connect('currentPathChanged(const QString&)', self.onOutputDirectoryPathLineEditChanged)
# Buttons
self.ui.startButton.connect('clicked(bool)', self.onStartButton)
self.ui.applyButton.connect('clicked(bool)', self.onApplyButton)
self.ui.cancelButton.connect('clicked(bool)', self.onCancelButton)
self.ui.updateIntensityButton.connect('clicked(bool)', self.onUpdateIntensityButton)
self.ui.setDefaultButton.connect('clicked(bool)', self.onSetDefaultButton)
self.ui.batchProcessingButton.connect('clicked(bool)', self.onBatchProcessingButton)
self.ui.cancelBatchProcessingButton.connect('clicked(bool)', self.onCancelBatchProcessingButton)
self.ui.toggleSegmentationVisibilityButton.connect('clicked(bool)', self.onToggleSegmentationVisibilityButton)
self.ui.toggleVolumeRenderingVisibilityButton.connect('clicked(bool)', self.onToggleVolumeRenderingVisibilityButton)
self.ui.engineAIComboBox.enabled = False
settings=qt.QSettings(slicer.app.launcherSettingsFilePath, qt.QSettings.IniFormat)
self.ui.inputDirectoryPathLineEdit.currentPath = settings.value("LungCtSegmenter/batchProcessingInputFolder", "")
self.ui.outputDirectoryPathLineEdit.currentPath = settings.value("LungCtSegmenter/batchProcessingOutputFolder", "")
if settings.value("LungCtSegmenter/lungThresholdRangeMinimumValue", "") != "":
self.ui.LungThresholdRangeWidget.minimumValue = self.lungThresholdMin = float(settings.value("LungCtSegmenter/lungThresholdRangeMinimumValue", ""))
if settings.value("LungCtSegmenter/lungThresholdRangeMaximumValue", "") != "":
self.ui.LungThresholdRangeWidget.maximumValue = self.lungThresholdMax = float(settings.value("LungCtSegmenter/lungThresholdRangeMaximumValue", ""))
if settings.value("LungCtSegmenter/airwayThresholdRangeMinimumValue", "") != "":
self.ui.AirwayThresholdRangeWidget.minimumValue = self.airwayThresholdMin = float(settings.value("LungCtSegmenter/airwayThresholdRangeMinimumValue", ""))
if settings.value("LungCtSegmenter/airwayThresholdRangeMaximumValue", "") != "":
self.ui.AirwayThresholdRangeWidget.maximumValue = self.airwayThresholdMax = float(settings.value("LungCtSegmenter/airwayThresholdRangeMaximumValue", ""))
if settings.value("LungCtSegmenter/vesselThresholdRangeMinimumValue", "") != "":
self.ui.VesselThresholdRangeWidget.minimumValue = self.vesselThresholdMin = float(settings.value("LungCtSegmenter/vesselThresholdRangeMinimumValue", ""))
if settings.value("LungCtSegmenter/vesselThresholdRangeMaximumValue", "") != "":
self.ui.VesselThresholdRangeWidget.maximumValue = self.vesselThresholdMax = float(settings.value("LungCtSegmenter/vesselThresholdRangeMaximumValue", ""))
if settings.value("LungCtSegmenter/testModeCheckBoxChecked", "") != "":
self.batchProcessingTestMode = eval(settings.value("LungCtSegmenter/testModeCheckBoxChecked", ""))
self.ui.testModeCheckBox.checked = eval(settings.value("LungCtSegmenter/testModeCheckBoxChecked", ""))
if settings.value("LungCtSegmenter/niigzFormatCheckBoxChecked", "") != "":
self.isNiiGzFormat = eval(settings.value("LungCtSegmenter/niigzFormatCheckBoxChecked", ""))
self.ui.niigzFormatCheckBox.checked = eval(settings.value("LungCtSegmenter/niigzFormatCheckBoxChecked", ""))
if settings.value("LungCtSegmenter/fastCheckBoxChecked", "") != "":
self.fastOption = eval(settings.value("LungCtSegmenter/fastCheckBoxChecked", ""))
self.ui.fastCheckBox.checked = eval(settings.value("LungCtSegmenter/fastCheckBoxChecked", ""))
if settings.value("LungCtSegmenter/smoothLungsCheckBoxChecked", "") != "":
self.smoothLungs = eval(settings.value("LungCtSegmenter/smoothLungsCheckBoxChecked", ""))
self.ui.smoothLungsCheckBox.checked = eval(settings.value("LungCtSegmenter/smoothLungsCheckBoxChecked", ""))
if settings.value("LungCtSegmenter/calibrateDataCheckBoxChecked", "") != "":
self.calibrateData = eval(settings.value("LungCtSegmenter/calibrateDataCheckBoxChecked", ""))
self.ui.calibrateDataCheckBox.checked = eval(settings.value("LungCtSegmenter/calibrateDataCheckBoxChecked", ""))
# Make sure parameter node is initialized (needed for module reload)
self.initializeParameterNode()
slicer.app.applicationLogic().FitSliceToAll()
# Initial GUI update
self.updateGUIFromParameterNode()
self.ui.toggleSegmentationVisibilityButton.enabled = False
self.ui.toggleVolumeRenderingVisibilityButton.enabled = False
self.ui.VolumeRenderingShiftSliderWidget.enabled = False
self.ui.fastCheckBox.enabled = False
self.ui.smoothLungsCheckBox.enabled = False
self.ui.batchProcessingCollapsibleButton.collapsed = True
self.ui.outputCollapsibleButton.collapsed = True
self.ui.calibrateDataCheckBox.enabled = False
def cleanup(self):
"""
Called when the application closes and the module widget is destroyed.
"""
self.removeFiducialObservers()
self.removeObservers()
# self.removeKeyboardShortcuts()
self.logic = None
def enter(self):
"""
Called each time the user opens this module.
"""
# Make sure parameter node exists and observed
self.initializeParameterNode()
def exit(self):
"""
Called each time the user opens a different module.
"""
# Do not react to parameter node changes (GUI will be updated when the user enters into the module)
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
self.removeFiducialObservers()
def onSceneStartClose(self, caller, event):
"""
Called just before the scene is closed.
"""
# Parameter node will be reset, do not use it anymore
self.setParameterNode(None)
self.removeFiducialObservers()
def removeFiducialObservers(self):
self.updateFiducialObservations(self._rightLungFiducials, None)
self.updateFiducialObservations(self._leftLungFiducials, None)
self.updateFiducialObservations(self._tracheaFiducials, None)
self._rightLungFiducials = None
self._leftLungFiducials = None
self._tracheaFiducials = None
def onSetDefaultButton(self):
self.ui.VolumeRenderingShiftSliderWidget.value = 0
self.ui.LungThresholdRangeWidget.minimumValue = -1500
self.ui.LungThresholdRangeWidget.maximumValue = -400
self.ui.AirwayThresholdRangeWidget.minimumValue = -1500
self.ui.AirwayThresholdRangeWidget.maximumValue = -700
self.ui.VesselThresholdRangeWidget.minimumValue = -0
self.ui.VesselThresholdRangeWidget.maximumValue = 3000
self.updateParameterNodeFromGUI()
def onInputDirectoryPathLineEditChanged(self):
self.batchProcessingInputDir = self.ui.inputDirectoryPathLineEdit.currentPath
settings=qt.QSettings(slicer.app.launcherSettingsFilePath, qt.QSettings.IniFormat)
settings.setValue("LungCtSegmenter/batchProcessingInputFolder", self.ui.inputDirectoryPathLineEdit.currentPath);
def onOutputDirectoryPathLineEditChanged(self):
self.batchProcessingOutputDir = self.ui.outputDirectoryPathLineEdit.currentPath
settings=qt.QSettings(slicer.app.launcherSettingsFilePath, qt.QSettings.IniFormat)
settings.setValue("LungCtSegmenter/batchProcessingOutputFolder", self.ui.outputDirectoryPathLineEdit.currentPath);
def showStatusMessage(self, msg, timeoutMsec=500):
slicer.util.showStatusMessage(msg, timeoutMsec)
slicer.app.processEvents()
def onCancelBatchProcessingButton(self):
print("Batch processing is cancelled by user.")
self.batchProcessingIsCancelled = True
def showCriticalError(self, msg):
slicer.util.messageBox(msg)
raise ValueError(msg)
def onBatchProcessingButton(self):
self.batchProcessingIsCancelled = False
if self.batchProcessingInputDir == "":
self.showCriticalError("No input directory given.")
if self.batchProcessingOutputDir == "":
self.showCriticalError("No output directory given.")
if self.batchProcessingInputDir == self.batchProcessingOutputDir:
self.showCriticalError("Input and output directotry can not be the same path.")
if not self.useAI:
self.showCriticalError("Batch processing can only be done with 'Use AI' checked.")
if self.createDetailedAirways and not (self.useAI and self.logic.engineAI.find("TotalSegmentator") == 0):
self.showCriticalError("Batch processing can not be used with Local Threshold airway analysis.")
if not os.path.exists(self.batchProcessingInputDir):
self.showCriticalError("Input folder does not exist.")
counter = 0
pattern = ''
if self.isNiiGzFormat:
pattern = '/' '**/*.nii.gz'
else:
pattern = '/' '**/*.nrrd'
filesToProcess = 0
for filename in glob.iglob(self.batchProcessingInputDir + pattern, recursive=True):
pathhead, pathtail = os.path.split(filename)
if (pathtail == "CT.nrrd" and not self.isNiiGzFormat) or (pathtail == "ct.nii.gz" and self.isNiiGzFormat):
# input data must be in subdirectories of self.batchProcessingInputDir
if pathhead == self.batchProcessingInputDir:
self.showCriticalError("Unsupported data structure: Data files in input folder detected, they must be placed in subfolders.")
# input data must be in immediate child directory of self.batchProcessingInputDir
parentDir = os.path.dirname(pathhead)
if parentDir != self.batchProcessingInputDir:
self.showCriticalError("Unsupported data structure: There seem to be input data in sub-subfolders of the input folder. Only one subfolder dimension is allowed.")
filesToProcess += 1
if self.batchProcessingTestMode:
print("Input file '" + filename + "' detected ...")
if filesToProcess == 0:
self.showCriticalError("No files to process. Each input file must be placed in a separate subdirectory of the input folder.")
minutesRequired = filesToProcess * 180 / 60
if not self.batchProcessingTestMode and not slicer.util.confirmYesNoDisplay("If each segmentation takes about 3 minutes, batch segmentation of " + str(filesToProcess) + " input files will last around " + str(minutesRequired) + " minutes. Are you sure you want to continue?"):
logging.info('Batch processing cancelled by user.')
return
if self.batchProcessingTestMode and filesToProcess < 3:
self.showCriticalError("Not enough input files for test mode (3 needed) during recursive reading below input directory path.")
startWatchTime = time.time()
counter = 0
durationProcess = 0
if self.batchProcessingTestMode:
filesToProcess = 3
for filename in glob.iglob(self.batchProcessingInputDir + pattern, recursive=True):
pathhead, pathtail = os.path.split(filename)
if (pathtail == "CT.nrrd" and not self.isNiiGzFormat) or (pathtail == "ct.nii.gz" and self.isNiiGzFormat) and pathhead != self.batchProcessingInputDir:
counter += 1
startProcessWatchTime = time.time()
slicer.mrmlScene.Clear(0)
self.inputVolume = slicer.util.loadVolume(filename)
print("Segmenting '" + filename + "' ...")
if self.useAI and (not self.createDetailedAirways or (self.createDetailedAirways and self.useAI and self.logic.engineAI.find("TotalSegmentator") == 0)):
self.onStartButton()
else:
print("Unable to batch segment CT, AI must be enabled and/or airway segmentation can not be checked.")
outpathhead, outpathtail = os.path.split(pathhead)
targetdir = self.batchProcessingOutputDir + "/" + outpathtail + "/"
if not os.path.exists(targetdir):
os.makedirs(targetdir)
if self.isNiiGzFormat:
self.showStatusMessage("Writing NIFTI output files for input " + str(counter) + "/" + str(filesToProcess) + " to '" + targetdir + "' ...")
for volumeNode in slicer.util.getNodesByClass("vtkMRMLScalarVolumeNode"):
volumeNode.AddDefaultStorageNode()
slicer.util.saveNode(volumeNode, targetdir + volumeNode.GetName() + "_source.nii.gz")
numberOfSegments = self.logic.outputSegmentation.GetSegmentation().GetNumberOfSegments()
for i in range(numberOfSegments):
segment = self.logic.outputSegmentation.GetSegmentation().GetNthSegment(i)
labelmapVolumeNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLabelMapVolumeNode")
segID = self.logic.outputSegmentation.GetSegmentation().GetSegmentIdBySegment(segment)
strArr = [str(segID)]
slicer.modules.segmentations.logic().ExportSegmentsToLabelmapNode (self.logic.outputSegmentation, strArr, labelmapVolumeNode, self.logic.inputVolume)
labelmapVolumeNode.AddDefaultStorageNode()
slicer.util.saveNode(labelmapVolumeNode, targetdir + segment.GetName().replace(" ", "_") + ".seg.nii.gz")
slicer.mrmlScene.RemoveNode(labelmapVolumeNode)
else:
sceneSaveFilename = targetdir + "CT_seg.mrb"
self.showStatusMessage("Writing mrb output file for input " + str(counter) + "/" + str(filesToProcess) + " (last process: {0:.2f} s ".format(durationProcess) + " processing and write time) to '" + sceneSaveFilename + "' ...")
print('Saving scene to ' + sceneSaveFilename)
if slicer.util.saveScene(sceneSaveFilename):
logging.info("Scene saved to: {0}".format(sceneSaveFilename))
else:
logging.error("Scene saving failed")
stopProcessWatchTime = time.time()
durationProcess = stopProcessWatchTime - startProcessWatchTime
# let slicer process events and update its display
slicer.app.processEvents()
time.sleep(3)
if self.batchProcessingIsCancelled:
break
if self.batchProcessingTestMode and counter > 2:
break
stopWatchTime = time.time()
if self.batchProcessingIsCancelled:
print('Batch processing cancelled after {0:.2f} seconds'.format(stopWatchTime-startWatchTime))
self.showStatusMessage("Batch processing cancelled.")
else:
print('Batch processing completed in {0:.2f} seconds'.format(stopWatchTime-startWatchTime))
self.showStatusMessage("Batch processing done.")
def onShiftSliderWidgetChanged(self):
self.updateParameterNodeFromGUI()
self.updateVolumeRendering()
def onLungThresholdRangeWidgetChanged(self):
self.updateParameterNodeFromGUI()
def onAirwayThresholdRangeWidgetChanged(self):
self.updateParameterNodeFromGUI()
def onVesselThresholdRangeWidgetChanged(self):
self.updateParameterNodeFromGUI()
def onSceneEndClose(self, caller, event):
"""
Called just after the scene is closed.
"""
# If this module is shown while the scene is closed then recreate a new parameter node immediately
if self.parent.isEntered:
self.initializeParameterNode()
def initializeParameterNode(self):
"""
Ensure parameter node exists and observed.
"""
# Parameter node stores all user choices in parameter values, node selections, etc.
# so that when the scene is saved and reloaded, these settings are restored.
self.logic = LungCTSegmenterLogic()
self.setParameterNode(self.logic.getParameterNode())
# Select default input nod#es if nothing is selected yet to save a few clicks for the user
if not self.logic.inputVolume:
firstVolumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode")
if firstVolumeNode:
self.logic.inputVolume = firstVolumeNode
# Set lung CT window / level of inputVolume
displayNode = self.logic.inputVolume.GetDisplayNode()
displayNode.AutoWindowLevelOff()
displayNode.SetWindowLevel(1400, -500)
#if not self.logic.outputSegmentation:
# firstSegmentationNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLSegmentationNode")
# if firstSegmentationNode:
# self.logic.outputSegmentation = firstSegmentationNode
def setParameterNode(self, inputParameterNode):
"""
Set and observe parameter node.
Observation is needed because when the parameter node is changed then the GUI must be updated immediately.
"""
if inputParameterNode:
self.logic.setDefaultParameters(inputParameterNode)
# Unobserve previously selected parameter node and add an observer to the newly selected.
# Changes of parameter node are observed so that whenever parameters are changed by a script or any other module
# those are reflected immediately in the GUI.
if self._parameterNode is not None:
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
self._parameterNode = inputParameterNode
if self._parameterNode is not None:
self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)
# Initial GUI update
self.updateGUIFromParameterNode()
def setInstructions(self, text):
#self.ui.instructionsLabel.text = f"<h1><b>{text}</b></h1>"
self.ui.instructionsLabel.setHtml(f"<h1><b>{text}</b></h1>")
slicer.app.processEvents()
def setInstructionPlaceMorePoints(self, location, startingFrom, target, current):
numberOfPointsToPlace = target - current
plural = "s" if numberOfPointsToPlace > 1 else ""
more = "more " if current > startingFrom else ""
self.setInstructions(f"Place {numberOfPointsToPlace} {more} point{plural} in the {location}.")
def updateGUIFromParameterNode(self, caller=None, event=None):
"""
This method is called whenever parameter node is changed.
The module GUI is updated to show the current state of the parameter node.
"""
if self._parameterNode is None or self._updatingGUIFromParameterNode:
return
# Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop)
self._updatingGUIFromParameterNode = True
# Update node selectors and sliders
self.ui.inputVolumeSelector.setCurrentNode(self.logic.inputVolume)
self.ui.outputSegmentationSelector.setCurrentNode(self.logic.outputSegmentation)
self.ui.rightLungPlaceWidget.setCurrentNode(self.logic.rightLungFiducials)
self.ui.leftLungPlaceWidget.setCurrentNode(self.logic.leftLungFiducials)
self.ui.tracheaPlaceWidget.setCurrentNode(self.logic.tracheaFiducials)
# Display instructions
isSufficientNumberOfPointsPlaced = False
if not self.logic.segmentationStarted or not self.logic.rightLungFiducials or not self.logic.leftLungFiducials or not self.logic.tracheaFiducials:
# Segmentation has not started yet
self.ui.adjustPointsGroupBox.enabled = False
if not self.logic.inputVolume:
self.setInstructions("Select input volume.")
else:
self.setInstructions('Click "Start" to initiate point placement.')
else:
slicer.app.processEvents()
rightLungF = self.logic.rightLungFiducials.GetNumberOfDefinedControlPoints()
leftLungF = self.logic.leftLungFiducials.GetNumberOfDefinedControlPoints()
tracheaF = self.logic.tracheaFiducials.GetNumberOfDefinedControlPoints()
#print(" R " + str(rightLungF) + " L " + str(leftLungF) + " T " + str(tracheaF))
# Segmentation is in progress
self.ui.adjustPointsGroupBox.enabled = True
if rightLungF < 3 and not self.useAI:
self.setInstructionPlaceMorePoints("right lung", 0, 3, rightLungF)
self.ui.rightLungPlaceWidget.placeModeEnabled = True
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpRedSliceView)
elif leftLungF < 3 and not self.useAI:
self.setInstructionPlaceMorePoints("left lung", 0, 3, leftLungF)
self.ui.leftLungPlaceWidget.placeModeEnabled = True
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpRedSliceView)
elif rightLungF < 6 and not self.useAI:
self.setInstructionPlaceMorePoints("right lung", 3, 6, rightLungF)
self.ui.rightLungPlaceWidget.placeModeEnabled = True
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView)
elif leftLungF < 6 and not self.useAI:
self.setInstructionPlaceMorePoints("left lung", 3, 6, leftLungF)
self.ui.leftLungPlaceWidget.placeModeEnabled = True
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView)
elif tracheaF < 1:
if self.useAI and not self.createDetailedAirways:
# no trachea markup needed, so skip placement
pass
elif self.createDetailedAirways and self.useAI and self.logic.engineAI.find("TotalSegmentator") == 0:
# markup will be generated from TS trachea centroid
pass
else:
self.setInstructionPlaceMorePoints("trachea", 0, 1, tracheaF)
self.ui.tracheaPlaceWidget.placeModeEnabled = True
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView)
else:
if self.useAI:
self.setInstructions('Click "Apply" to finalize.')
self.ui.tracheaPlaceWidget.placeModeEnabled = False
self.ui.adjustPointsGroupBox.enabled = True
else:
self.setInstructions('Verify that segmentation is complete. Click "Apply" to finalize.')
slicer.app.layoutManager().setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpView)
self.isSufficientNumberOfPointsPlaced = True
self.ui.startButton.enabled = not self.logic.segmentationStarted
self.ui.cancelButton.enabled = self.logic.segmentationStarted
self.ui.updateIntensityButton.enabled = self.logic.segmentationStarted
self.ui.applyButton.enabled = self.isSufficientNumberOfPointsPlaced
if self.logic.segmentationFinished:
self.ui.applyButton.enabled = False
self.ui.cancelButton.enabled = True
self.ui.startButton.enabled = False
self.ui.detailedAirwaysCheckBox.checked = self.createDetailedAirways
self.ui.createVesselsCheckBox.checked = self.createVessels
self.ui.useAICheckBox.checked = self.useAI
self.ui.fastCheckBox.checked = self.fastOption
self.ui.smoothLungsCheckBox.checked = self.smoothLungs
self.ui.calibrateDataCheckBox.checked = self.calibrateData
self.ui.testModeCheckBox.checked = self.batchProcessingTestMode
self.ui.niigzFormatCheckBox.checked = self.isNiiGzFormat
self.ui.shrinkMasksCheckBox.checked = self.shrinkMasks
self.ui.detailedMasksCheckBox.checked = self.detailedMasks
self.ui.saveFiducialsCheckBox.checked = self.saveFiducials
self.ui.detailLevelComboBox.currentText = self.logic.airwaySegmentationDetailLevel
self.ui.engineAIComboBox.currentText = self.logic.engineAI
self.ui.VolumeRenderingShiftSliderWidget.value = self.VolumeRenderingShift
self.ui.LungThresholdRangeWidget.minimumValue = self.lungThresholdMin
self.ui.LungThresholdRangeWidget.maximumValue = self.lungThresholdMax
self.ui.AirwayThresholdRangeWidget.minimumValue = self.airwayThresholdMin
self.ui.AirwayThresholdRangeWidget.maximumValue = self.airwayThresholdMax
self.ui.VesselThresholdRangeWidget.minimumValue = self.vesselThresholdMin
self.ui.VesselThresholdRangeWidget.maximumValue = self.vesselThresholdMax
self.updateFiducialObservations(self._rightLungFiducials, self.logic.rightLungFiducials)
self.updateFiducialObservations(self._leftLungFiducials, self.logic.leftLungFiducials)
self.updateFiducialObservations(self._tracheaFiducials, self.logic.tracheaFiducials)
self._rightLungFiducials = self.logic.rightLungFiducials
self._leftLungFiducials = self.logic.leftLungFiducials
self._tracheaFiducials = self.logic.tracheaFiducials
# All the GUI updates are done
self._updatingGUIFromParameterNode = False
def updateFiducialObservations(self, oldFiducial, newFiducial):
if oldFiducial == newFiducial:
return
if oldFiducial:
self.removeObserver(oldFiducial, slicer.vtkMRMLMarkupsNode.PointPositionDefinedEvent, self.updateSeeds)
self.removeObserver(oldFiducial, slicer.vtkMRMLMarkupsNode.PointPositionUndefinedEvent, self.updateSeeds)
if newFiducial:
self.addObserver(newFiducial, slicer.vtkMRMLMarkupsNode.PointPositionDefinedEvent, self.updateSeeds)
self.addObserver(newFiducial, slicer.vtkMRMLMarkupsNode.PointPositionUndefinedEvent, self.updateSeeds)
def updateSeeds(self, caller, eventId):
# Lock all fiducials - add/remove them instead of moving (if markup is moved then we would need to reinitialize
# region growing, which would take time)
slicer.modules.markups.logic().SetAllControlPointsLocked(caller, True)
self.updateGUIFromParameterNode()
if self.isSufficientNumberOfPointsPlaced:
self.logic.updateSegmentation()
def updateParameterNodeFromGUI(self, caller=None, event=None):
"""
This method is called when the user makes any change in the GUI.
The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded).
"""
if self._parameterNode is None or self.logic is None or self._updatingGUIFromParameterNode:
return
wasModified = self._parameterNode.StartModify() # Modify all properties in a single batch
settings=qt.QSettings(slicer.app.launcherSettingsFilePath, qt.QSettings.IniFormat)
self.logic.inputVolume = self.ui.inputVolumeSelector.currentNode()
self.logic.outputSegmentation = self.ui.outputSegmentationSelector.currentNode()
self.VolumeRenderingShift = self.ui.VolumeRenderingShiftSliderWidget.value
self.lungThresholdMin = self.ui.LungThresholdRangeWidget.minimumValue
settings.setValue("LungCtSegmenter/lungThresholdRangeMinimumValue", str(self.ui.LungThresholdRangeWidget.minimumValue))
self.lungThresholdMax = self.ui.LungThresholdRangeWidget.maximumValue
settings.setValue("LungCtSegmenter/lungThresholdRangeMaximumValue", str(self.ui.LungThresholdRangeWidget.maximumValue))
self.airwayThresholdMin = self.ui.AirwayThresholdRangeWidget.minimumValue
settings.setValue("LungCtSegmenter/airwayThresholdRangeMinimumValue", str(self.ui.AirwayThresholdRangeWidget.minimumValue))
self.airwayThresholdMax = self.ui.AirwayThresholdRangeWidget.maximumValue
settings.setValue("LungCtSegmenter/airwayThresholdRangeMaximumValue", str(self.ui.AirwayThresholdRangeWidget.maximumValue))
self.vesselThresholdMin = self.ui.VesselThresholdRangeWidget.minimumValue
settings.setValue("LungCtSegmenter/vesselThresholdRangeMinimumValue", str(self.ui.VesselThresholdRangeWidget.minimumValue))
self.vesselThresholdMax = self.ui.VesselThresholdRangeWidget.maximumValue
settings.setValue("LungCtSegmenter/vesselThresholdRangeMaximumValue", str(self.ui.VesselThresholdRangeWidget.maximumValue))
self.createDetailedAirways = self.ui.detailedAirwaysCheckBox.checked
self.createVessels = self.ui.createVesselsCheckBox.checked
self.useAI = self.ui.useAICheckBox.checked
self.fastOption = self.ui.fastCheckBox.checked
settings.setValue("LungCtSegmenter/fastCheckBoxChecked", str(self.smoothLungs))
self.batchProcessingTestMode = self.ui.testModeCheckBox.checked
settings.setValue("LungCtSegmenter/testModeCheckBoxChecked", str(self.batchProcessingTestMode))
self.isNiiGzFormat = self.ui.niigzFormatCheckBox.checked
settings.setValue("LungCtSegmenter/niigzFormatCheckBoxChecked", str(self.isNiiGzFormat))
self.smoothLungs = self.ui.smoothLungsCheckBox.checked
settings.setValue("LungCtSegmenter/smoothLungsCheckBoxChecked", str(self.smoothLungs))
self.calibrateData = self.ui.calibrateDataCheckBox.checked
settings.setValue("LungCtSegmenter/calibrateDataCheckBoxChecked", str(self.calibrateData))
self.ui.engineAIComboBox.enabled = self.useAI
self.shrinkMasks = self.ui.shrinkMasksCheckBox.checked
self.detailedMasks = self.ui.detailedMasksCheckBox.checked
self.saveFiducials = self.ui.saveFiducialsCheckBox.checked
self.logic.airwaySegmentationDetailLevel = self.ui.detailLevelComboBox.currentText
self.logic.engineAI = self.ui.engineAIComboBox.currentText
if self.logic.engineAI.find("TotalSegmentator") == 0:
self.ui.fastCheckBox.enabled = True
self.ui.calibrateDataCheckBox.enabled = True
else:
self.ui.fastCheckBox.enabled = False
self.ui.calibrateDataCheckBox.enabled = False
if self.useAI:
self.ui.LungThresholdRangeWidget.enabled = False
self.ui.smoothLungsCheckBox.enabled = True
else:
self.ui.LungThresholdRangeWidget.enabled = True
self.ui.smoothLungsCheckBox.enabled = False
self.setOutputVisibilityFromCheckBoxes()
self._parameterNode.EndModify(wasModified)
def onToggleSegmentationVisibilityButton(self):
"""
Toggle segmentation visibility.
"""
segmentationNode = self.logic.outputSegmentation
segmentationNode.CreateDefaultDisplayNodes()
segmentationDisplayNode = segmentationNode.GetDisplayNode()
if segmentationDisplayNode.GetVisibility2D():
segmentationDisplayNode.Visibility2DOff()
segmentationDisplayNode.Visibility3DOff()
else:
segmentationDisplayNode.Visibility2DOn()
segmentationDisplayNode.Visibility3DOn()
def updateVolumeRendering(self):
"""
Update Volume rendering
"""
if not self.logic.maskedVolume:
self.logic.maskedVolume = slicer.mrmlScene.GetFirstNodeByName(self.logic.inputVolume.GetName() + f' masked volume')
if not self.logic.maskedVolume:
slicer.util.warningDisplay("No masked volume found.\n")
return
volRenLogic = slicer.modules.volumerendering.logic()
self.volumeRenderingDisplayNode = volRenLogic.CreateDefaultVolumeRenderingNodes(self.logic.maskedVolume)
self.volumeRenderingDisplayNode.SetVisibility(True)
self.volumeRenderingDisplayNode.GetVolumePropertyNode().Copy(volRenLogic.GetPresetByName("CT-Coronary-Arteries-3"))
volRenWidget = slicer.modules.volumerendering.widgetRepresentation()
if volRenWidget is None:
logging.error('Failed to access volume rendering module')
return
# Make sure the proper volume property node is set
volumePropertyNode = self.volumeRenderingDisplayNode.GetVolumePropertyNode()
if volumePropertyNode is None:
logging.error('Failed to access volume properties')
return
volumePropertyNodeWidget = slicer.util.findChild(volRenWidget, 'VolumePropertyNodeWidget')
volumePropertyNodeWidget.setMRMLVolumePropertyNode(volumePropertyNode)
# Adjust the transfer function
volumePropertyNodeWidget.moveAllPoints(self.VolumeRenderingShift, 0, False)
def onToggleVolumeRenderingVisibilityButton(self):
"""
Toggle volume rendering visibility and handle vesselmask visibility.
"""
if not self.logic.maskedVolume:
self.logic.maskedVolume = slicer.mrmlScene.GetFirstNodeByName(self.logic.inputVolume.GetName() + f' masked volume')
if not self.logic.maskedVolume:
slicer.util.warningDisplay("No masked volume found.\n")
return
segmentation = self.logic.outputSegmentation.GetSegmentation()
_vesselmaskID = segmentation.GetSegmentIdBySegmentName("vesselmask")
if not self.volumeRenderingDisplayNode:
self.updateVolumeRendering()
if _vesselmaskID:
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(_vesselmaskID,False)
else:
if not self.volumeRenderingDisplayNode.GetVisibility():
self.volumeRenderingDisplayNode.SetVisibility(True)
if _vesselmaskID:
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(_vesselmaskID,False)
else:
self.volumeRenderingDisplayNode.SetVisibility(False)
if _vesselmaskID:
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(_vesselmaskID,True)
def onStartButton(self):
"""
Run processing when user clicks "Start" button.
"""
if not self.logic.inputVolume:
slicer.util.warningDisplay("Please load and select an input volume!\n")
return
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
try:
if self.ui.loadLastFiducialsCheckBox.checked:
# always try loading markups from data directory first
fiducialsLoadSuccess = self.loadFiducialsDataDir()
if not fiducialsLoadSuccess:
# otherwise try loading markups from temp directory
fiducialsLoadSuccess = self.loadFiducialsTempDir()
self.setInstructions("Initializing segmentation...")
self.isSufficientNumberOfPointsPlaced = False
self.ui.updateIntensityButton.enabled = True
self.logic.startSegmentation()
self.logic.updateSegmentation()
self.updateGUIFromParameterNode()
self.ui.toggleSegmentationVisibilityButton.enabled = False
self.ui.toggleVolumeRenderingVisibilityButton.enabled = False
self.ui.VolumeRenderingShiftSliderWidget.enabled = False
# if AI checked and no airway segmentation planned no need to place markups so
# run processing immediately from the start button
if (self.useAI and not self.createDetailedAirways) or (self.useAI and self.createDetailedAirways and self.logic.engineAI.find("TotalSegmentator") == 0):
self.runProcessing()
qt.QApplication.restoreOverrideCursor()
except Exception as e:
qt.QApplication.restoreOverrideCursor()
slicer.util.errorDisplay("Failed to start segmentation: "+str(e))
import traceback
traceback.print_exc()
def enableOutputCheckBox(self,labelname,_checked):
self.outputCheckBoxesDict[labelname].enabled = True
self.outputCheckBoxesDict[labelname].checked = _checked
def disableOutputCheckBox(self,labelname):
self.outputCheckBoxesDict[labelname].enabled = False
def disableAllOutputCheckBoxes(self):
for key, uiid in self.outputCheckBoxesDict.items():
uiid.checked = False
uiid.enabled = False
def setOutputVisibilityFromCheckBoxes(self):
if self.logic.outputSegmentation:
for key, uiid in self.outputCheckBoxesDict.items():
if uiid.enabled:
if key == "ribs right":
for i in range(1, 13):
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName("right rib " + str(i))
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
elif key == "ribs left":
for i in range(1, 13):
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName("left rib " + str(i))
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
elif key == "airways":
if self.logic.engineAI.find("TotalSegmentator") == 0:
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName("trachea")
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName("airways and bronchi")
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
else:
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName(key)
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
else:
segmentation = self.logic.outputSegmentation.GetSegmentation()
structureID = segmentation.GetSegmentIdBySegmentName(key)
self.logic.outputSegmentation.GetDisplayNode().SetSegmentVisibility(structureID,uiid.checked)
def runProcessing(self):
"""
Run processing
"""
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
self.ui.updateIntensityButton.enabled = False
try:
self.logic.lungThresholdMin = self.lungThresholdMin
self.logic.lungThresholdMax = self.lungThresholdMax
self.logic.airwayThresholdMin = self.airwayThresholdMin
self.logic.airwayThresholdMax = self.airwayThresholdMax
self.logic.vesselThresholdMin = self.vesselThresholdMin
self.logic.vesselThresholdMax = self.vesselThresholdMax
self.logic.detailedAirways = self.createDetailedAirways
self.logic.createVessels = self.createVessels
self.logic.useAI = self.useAI
self.logic.create3D = True
self.logic.smoothLungs = True
self.logic.fastOption = self.fastOption
self.logic.smoothLungs = self.smoothLungs
self.logic.calibrateData = self.calibrateData
if self.useAI:
self.logic.engineAI = self.ui.engineAIComboBox.currentText
# always save a copy of the current markups in Slicer temp dir for later use
self.saveFiducialsTempDir()
if self.saveFiducials:
self.saveFiducialsDataDir()
self.setInstructions('Finalizing the segmentation, please wait...')
self.logic.shrinkMasks = self.shrinkMasks
self.logic.detailedMasks = self.detailedMasks
self.disableAllOutputCheckBoxes()
self.logic.applySegmentation()
segmentationNode = self.logic.outputSegmentation
segmentationNode.CreateDefaultDisplayNodes()
segmentationDisplayNode = segmentationNode.GetDisplayNode()
segmentationDisplayNode.Visibility2DOn()
segmentationDisplayNode.Visibility3DOn()
self.volumeRenderingDisplayNode = None
self.updateGUIFromParameterNode()
self.ui.toggleSegmentationVisibilityButton.enabled = True
self.ui.toggleVolumeRenderingVisibilityButton.enabled = True
self.ui.VolumeRenderingShiftSliderWidget.enabled = True
qt.QApplication.restoreOverrideCursor()
except Exception as e:
qt.QApplication.restoreOverrideCursor()
slicer.util.errorDisplay("Failed to compute results: "+str(e))
import traceback
traceback.print_exc()
self.setInstructions('')
self.ui.applyButton.enabled = False
self.ui.outputCollapsibleButton.collapsed = False
self.enableOutputCheckBox("tumor", False)
if self.createVessels:
self.enableOutputCheckBox("vesselmask", True)
self.enableOutputCheckBox("PA", True)
self.enableOutputCheckBox("PV", True)
if self.createDetailedAirways:
self.enableOutputCheckBox("airways", True)
if not self.useAI:
self.enableOutputCheckBox("right lung", True)
self.enableOutputCheckBox("left lung", True)
else:
if self.logic.engineAI == "TotalSegmentator lung extended":
self.enableOutputCheckBox("ribs right", False)
self.enableOutputCheckBox("ribs left",False)
if self.logic.engineAI == "TotalSegmentator lung extended" or self.logic.engineAI == "TotalSegmentator lung basic" or self.logic.engineAI == "lungmask LTRCLobes" or self.logic.engineAI == "lungmask LTRCLobes_R231" or self.logic.engineAI == "MONAILabel" :
if not self.logic.engineAI.find("lungmask") == 0:
self.enableOutputCheckBox("airways", True)
self.enableOutputCheckBox("right upper lobe",True)
self.enableOutputCheckBox("right middle lobe",True)
self.enableOutputCheckBox("right lower lobe",True)
self.enableOutputCheckBox("left upper lobe",True)
self.enableOutputCheckBox("left lower lobe",True)
self.enableOutputCheckBox("right lung",False)
self.enableOutputCheckBox("left lung",False)
else:
self.enableOutputCheckBox("right lung",True)
self.enableOutputCheckBox("left lung",True)
def onApplyButton(self):
"""
Run processing when user clicks "Apply" button.
"""