-
Notifications
You must be signed in to change notification settings - Fork 12
/
SimpleFilters.py
1110 lines (848 loc) · 35.8 KB
/
SimpleFilters.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,sys
import unittest
from __main__ import vtk, qt, ctk, slicer
from glob import glob
import json
from collections import OrderedDict
import re
import threading
import Queue
from time import sleep
# To avoid the overhead of importing SimpleITK during application
# startup, the import of SimpleITK is delayed until it is needed.
sitk = None
sitkUtils = None
#
# SimpleFilters
#
class SimpleFilters:
# Use class-level scoped variable for module consants
if not __file__.endswith("SimpleFilters.py"):
import inspect
__file__ = inspect.getframeinfo(inspect.currentframe())[0]
ICON_DIR = os.path.dirname(os.path.realpath(__file__)) + '/Resources/Icons/'
JSON_DIR = os.path.dirname(os.path.realpath(__file__)) + '/Resources/json/'
def __init__(self, parent):
parent.title = "Simple Filters"
parent.categories = ["Filtering"]
parent.dependencies = []
parent.contributors = ["Bradley Lowekamp (MSC/NLM), Steve Pieper (Isomics), Jean-Christophe Fillion-Robin (Kitware)"]
parent.helpText = \
"""
This modules provides a basic interface to 250 image filters from the
Insight Toolkit. It provides access to algorithms such as binary
morphology, grayscale morphology, region growing, smoothing, denosing,
distance fields, FFTs, convolutions, automatic thresholding, intensity
math and many advanced algorithms.
<br /><br />
Most algorithms which take multiple input images expect the inputs to
have the same physical locations (spacing, origin, orientation and
largest possible region), and be the same pixel type.
<br /><br />
For general information about the module see the <a href=\"{0}/Documentation/Nightly/Modules/SimpleFilters\">online documentation</a>.
<br /><br />
For detailed information about a specific filter please consult the <a href=\"http://www.itk.org/Doxygen/html/\">Insight Toolkit Doxygen</a>.
""".format(parent.slicerWikiUrl, slicer.app.majorVersion, slicer.app.minorVersion)
parent.acknowledgementText = """
The developers would like to thank the support of the Slicer Community, the Insight Toolkit and the ITK Community."
""" # replace with organization, grant and thanks.
self.parent = parent
parent.icon = qt.QIcon("%s/ITK.png" % self.ICON_DIR)
#
# qSimpleFiltersWidget
#
class SimpleFiltersWidget:
def __init__(self, parent = None):
# To avoid the overhead of importing SimpleITK during application
# startup, the import of SimpleITK is delayed until it is needed.
global sitk
import SimpleITK as sitk
global sitkUtils
import sitkUtils
if not parent:
self.parent = slicer.qMRMLWidget()
self.parent.setLayout(qt.QVBoxLayout())
self.parent.setMRMLScene(slicer.mrmlScene)
else:
self.parent = parent
self.layout = self.parent.layout()
if not parent:
self.setup()
self.parent.show()
jsonFiles = glob(SimpleFilters.JSON_DIR+"*.json")
jsonFiles.sort(cmp=lambda x,y: cmp(os.path.basename(x), os.path.basename(y)))
self.jsonFilters = []
for fname in jsonFiles:
try:
fp = file(fname, "r")
j = json.load(fp,object_pairs_hook=OrderedDict)
if j["name"] in dir(sitk):
self.jsonFilters.append(j)
else:
import sys
sys.stderr.write("Unknown SimpleITK class \"{0}\".\n".format(j["name"]))
except Exception as e:
import sys
sys.stderr.write("Error while reading \"{0}\". Exception: {1}\n".format(fname, e))
self.filterParameters = None
self.logic = None
def setup(self):
# Instantiate and connect widgets ...
#
# Filters Area
#
filtersCollapsibleButton = ctk.ctkCollapsibleButton()
filtersCollapsibleButton.text = "Filters"
self.layout.addWidget(filtersCollapsibleButton)
# Layout within the dummy collapsible button
filtersFormLayout = qt.QFormLayout(filtersCollapsibleButton)
# filter search
self.searchBox = ctk.ctkSearchBox()
filtersFormLayout.addRow("Search:", self.searchBox)
self.searchBox.connect("textChanged(QString)", self.onSearch)
# filter selector
self.filterSelector = qt.QComboBox()
filtersFormLayout.addRow("Filter:", self.filterSelector)
# add all the filters listed in the json files
for idx,j in enumerate(self.jsonFilters):
name = j["name"]
self.filterSelector.addItem(name, idx)
# connections
self.filterSelector.connect('currentIndexChanged(int)', self.onFilterSelect)
#
# Parameters Area
#
parametersCollapsibleButton = ctk.ctkCollapsibleButton()
parametersCollapsibleButton.text = "Parameters"
self.layout.addWidget(parametersCollapsibleButton)
# Layout within the dummy collapsible button
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
self.filterParameters = FilterParameters(parametersCollapsibleButton)
# Add vertical spacer
self.layout.addStretch(1)
#
# Status and Progress
#
statusLabel = qt.QLabel("Status: ")
self.currentStatusLabel = qt.QLabel("Idle")
hlayout = qt.QHBoxLayout()
hlayout.addStretch(1)
hlayout.addWidget(statusLabel)
hlayout.addWidget(self.currentStatusLabel)
self.layout.addLayout(hlayout)
self.progress = qt.QProgressBar()
self.progress.setRange(0,1000)
self.progress.setValue(0)
self.layout.addWidget(self.progress)
self.progress.hide()
#
# Cancel/Apply Row
#
self.restoreDefaultsButton = qt.QPushButton("Restore Defaults")
self.restoreDefaultsButton.toolTip = "Restore the default parameters."
self.restoreDefaultsButton.enabled = True
self.cancelButton = qt.QPushButton("Cancel")
self.cancelButton.toolTip = "Abort the algorithm."
self.cancelButton.enabled = False
self.applyButton = qt.QPushButton("Apply")
self.applyButton.toolTip = "Run the algorithm."
self.applyButton.enabled = True
hlayout = qt.QHBoxLayout()
hlayout.addWidget(self.restoreDefaultsButton)
hlayout.addStretch(1)
hlayout.addWidget(self.cancelButton)
hlayout.addWidget(self.applyButton)
self.layout.addLayout(hlayout)
# connections
self.restoreDefaultsButton.connect('clicked(bool)', self.onRestoreDefaultsButton)
self.applyButton.connect('clicked(bool)', self.onApplyButton)
self.cancelButton.connect('clicked(bool)', self.onCancelButton)
# Initlial Selection
self.filterSelector.currentIndexChanged(self.filterSelector.currentIndex)
def cleanup(self):
pass
def printPythonCommand(self):
#self.filterParameters.prerun() # Do this first!
printStr = []
currentFilter = self.filterParameters.filter
varName = currentFilter.__class__.__name__
printStr.append('myFilter = {0}()'.format(varName))
for key in dir(currentFilter):
if key == 'GetName' or key.startswith('GetGlobal'):
pass
elif key[:3] == 'Get':
setAttr = key.replace("Get", "Set", 1)
if hasattr(currentFilter, setAttr):
value = eval("currentFilter.{0}()".format( key))
printStr.append('myFilter.{0}({1})'.format(setAttr, value))
print "\n".join(printStr)
def onLogicRunStop(self):
self.applyButton.setEnabled(True)
self.restoreDefaultsButton.setEnabled(True)
self.cancelButton.setEnabled(False)
self.logic = None
self.progress.hide()
def onLogicRunStart(self):
self.applyButton.setEnabled(False)
self.restoreDefaultsButton.setEnabled(False)
def onSearch(self, searchText):
# add all the filters listed in the json files
self.filterSelector.clear()
# split text on whitespace of and string search
searchTextList = searchText.split()
for idx,j in enumerate(self.jsonFilters):
lname = j["name"].lower()
# require all elements in list, to add to select. case insensitive
if reduce(lambda x, y: x and (lname.find(y.lower())!=-1), [True]+searchTextList):
self.filterSelector.addItem(j["name"],idx)
def onFilterSelect(self, selectorIndex):
self.filterParameters.destroy()
if selectorIndex < 0:
return
jsonIndex= self.filterSelector.itemData(selectorIndex)
json = self.jsonFilters[jsonIndex]
self.filterParameters.create(json)
if "briefdescription" in self.jsonFilters[jsonIndex]:
tip=self.jsonFilters[jsonIndex]["briefdescription"]
tip=tip.rstrip()
self.filterSelector.setToolTip(tip)
else:
self.filterSelector.setToolTip("")
def onRestoreDefaultsButton(self):
self.onFilterSelect(self.filterSelector.currentIndex)
def onApplyButton(self):
try:
self.currentStatusLabel.text = "Starting"
self.filterParameters.prerun()
self.logic = SimpleFiltersLogic()
self.printPythonCommand()
#print "running..."
self.logic.run(self.filterParameters.filter,
self.filterParameters.output,
self.filterParameters.outputLabelMap,
*self.filterParameters.inputs)
except:
self.currentStatusLabel.text = "Exception"
import sys
msg = sys.exc_info()[0]
# if there was an exception during start-up make sure to finish
self.onLogicRunStop()
qt.QMessageBox.critical(slicer.util.mainWindow(),
"Exception before execution of {0}".format(self.filterParameters.filter.GetName()),
msg)
def onCancelButton(self):
self.currentStatusLabel.text = "Aborting"
if self.logic:
self.logic.abort = True;
def onLogicEventStart(self):
self.currentStatusLabel.text = "Running"
self.cancelButton.setDisabled(False)
self.progress.setValue(0)
self.progress.show()
def onLogicEventEnd(self):
self.currentStatusLabel.text = "Completed"
self.progress.setValue(1000)
def onLogicEventAbort(self):
#print "Aborting..."
self.currentStatusLabel.text = "Aborted"
def onLogicEventProgress(self, progress):
self.currentStatusLabel.text = "Running ({0:6.5f})".format(progress)
self.progress.setValue(progress*1000)
def onLogicEventIteration(self, nIter):
print "Iteration " , nIter
#
# SimpleFiltersLogic
#
class SimpleFiltersLogic:
"""This class should implement all the actual
computation done by your module. The interface
should be such that other python code can import
this class and make use of the functionality without
requiring an instance of the Widget
"""
def __init__(self):
self.main_queue = Queue.Queue()
self.main_queue_running = False
self.thread = threading.Thread()
self.abort = False
def __del__(self):
if self.main_queue_running:
self.main_queue_stop()
if self.thread.is_alive():
self.thread.join()
def yieldPythonGIL(self, seconds=0):
sleep(seconds)
def cmdCheckAbort(self, sitkFilter):
if self.abort:
sitkFilter.Abort()
def cmdStartEvent(self, sitkFilter):
#print "cmStartEvent"
widget = slicer.modules.SimpleFiltersWidget
self.main_queue.put(lambda: widget.onLogicEventStart())
self.yieldPythonGIL()
def cmdProgressEvent(self, sitkFilter):
#print "cmProgressEvent", sitkFilter.GetProgress()
widget = slicer.modules.SimpleFiltersWidget
self.main_queue.put(lambda p=sitkFilter.GetProgress(): widget.onLogicEventProgress(p))
self.cmdCheckAbort(sitkFilter)
self.yieldPythonGIL()
def cmdIterationEvent(self, sitkFilter, nIter):
print "cmIterationEvent"
widget = slicer.modules.SimpleFiltersWidget
self.main_queue.put(lambda: widget.onLogicEventIteration(nIter))
++nIter;
self.cmdCheckAbort(sitkFilter)
self.yieldPythonGIL()
def cmdAbortEvent(self, sitkFilter):
#print "cmAbortEvent"
widget = slicer.modules.SimpleFiltersWidget
self.main_queue.put(lambda: widget.onLogicEventAbort())
self.yieldPythonGIL()
def cmdEndEvent(self):
#print "cmEndEvent"
widget = slicer.modules.SimpleFiltersWidget
self.main_queue.put(lambda: widget.onLogicEventEnd())
self.yieldPythonGIL()
def thread_doit(self,sitkFilter,*inputImages):
try:
nIter = 0
try:
sitkFilter.AddCommand(sitk.sitkStartEvent, lambda: self.cmdStartEvent(sitkFilter))
sitkFilter.AddCommand(sitk.sitkProgressEvent, lambda: self.cmdProgressEvent(sitkFilter))
sitkFilter.AddCommand(sitk.sitkIterationEvent, lambda: self.cmdIterationEvent(sitkFilter,nIter))
sitkFilter.AddCommand(sitk.sitkAbortEvent, lambda: self.cmdAbortEvent(sitkFilter))
sitkFilter.AddCommand(sitk.sitkEndEvent, lambda: self.cmdEndEvent())
except:
import sys
print "Unexpected error:", sys.exc_info()[0]
img = sitkFilter.Execute(*inputImages)
if not self.abort:
self.main_queue.put(lambda img=img:self.updateOutput(img))
except Exception as e:
msg = e.message
self.abort = True
self.yieldPythonGIL()
self.main_queue.put(lambda :qt.QMessageBox.critical(slicer.util.mainWindow(),
"Exception during execution of {0}".format(sitkFilter.GetName()),
msg))
finally:
# this filter is persistent, remove commands
sitkFilter.RemoveAllCommands()
self.main_queue.put(self.main_queue_stop)
def main_queue_start(self):
"""Begins monitoring of main_queue for callables"""
self.main_queue_running = True
slicer.modules.SimpleFiltersWidget.onLogicRunStart()
qt.QTimer.singleShot(0, self.main_queue_process)
def main_queue_stop(self):
"""End monitoring of main_queue for callables"""
self.main_queue_running = False
if self.thread.is_alive():
self.thread.join()
slicer.modules.SimpleFiltersWidget.onLogicRunStop()
def main_queue_process(self):
"""processes the main_queue of callables"""
try:
while not self.main_queue.empty():
f = self.main_queue.get_nowait()
if callable(f):
f()
if self.main_queue_running:
# Yield the GIL to allow other thread to do some python work.
# This is needed since pyQt doesn't yield the python GIL
self.yieldPythonGIL(.01)
qt.QTimer.singleShot(0, self.main_queue_process)
except Exception as e:
import sys
sys.stderr.write("FilterLogic error in main_queue: \"{0}\"".format(e))
# if there was an error try to resume
if not self.main_queue.empty() or self.main_queue_running:
qt.QTimer.singleShot(0, self.main_queue_process)
def updateOutput(self,img):
nodeWriteAddress=sitkUtils.GetSlicerITKReadWriteAddress(self.outputNodeName)
sitk.WriteImage(img,nodeWriteAddress)
node = slicer.util.getNode(self.outputNodeName)
applicationLogic = slicer.app.applicationLogic()
selectionNode = applicationLogic.GetSelectionNode()
if self.outputLabelMap:
selectionNode.SetReferenceActiveLabelVolumeID(node.GetID())
else:
selectionNode.SetReferenceActiveVolumeID(node.GetID())
applicationLogic.PropagateVolumeSelection(0)
applicationLogic.FitSliceToAll()
def run(self, filter, outputMRMLNode, outputLabelMap, *inputs):
"""
Run the actual algorithm
"""
if self.thread.is_alive():
import sys
sys.stderr.write("FilterLogic is already executing!")
return
inputImages = []
for i in inputs:
if i is None:
break
imgNodeName = i.GetName()
img = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(imgNodeName) )
inputImages.append(img)
self.output = None
# check
self.outputNodeName = outputMRMLNode.GetName()
self.outputLabelMap = outputLabelMap
self.abort = False
self.thread = threading.Thread( target=lambda f=filter,i=inputImages:self.thread_doit(f,*inputImages))
self.main_queue_start()
self.thread.start()
#
# Class to manage parameters
#
class FilterParameters(object):
""" This class is for managing the widgets for the parameters for a filter
"""
# class-scope regular expression to help covert from CamelCase
reCamelCase = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
def __init__(self, parent=None):
self.parent = parent
self.widgets = []
self.json = json
self.filter = None
self.inputs = []
self.output = None
self.prerun_callbacks = []
self.outputLabelMap = False
self.outputSelector = None
self.outputLabelMapBox = None
def __del__(self):
self.widgets = []
def BeautifyCamelCase(self, str):
return self.reCamelCase.sub(r' \1',str)
def create(self, json):
if not self.parent:
raise "no parent"
parametersFormLayout = self.parent.layout()
# You can't use exec in a function that has a subfunction, unless you specify a context.
exec( 'self.filter = sitk.{0}()'.format(json["name"])) in globals(), locals()
self.prerun_callbacks = []
self.inputs = []
self.outputLabelMap = False
#
# input volume selectors
#
if "inputs" in json:
# have named inputs
n=0
for input in json["inputs"]:
w = self.createInputWidget(n, noneEnabled=("optional" in input and input["optional"]))
name = "Input Volume: "
if "name" in input:
name = "Input {0}: ".format(input["name"])
name = name.replace("Image", "Volume")
print "adding {1}: {0}".format(name,n)
inputSelectorLabel = qt.QLabel(name)
self.widgets.append(inputSelectorLabel)
# add to layout after connection
parametersFormLayout.addRow(inputSelectorLabel, w)
self.inputs.append(w.currentNode())
n+=1
if "number_of_inputs" in json and json["number_of_inputs"] != 0:
import sys
sys.stderr.write("Expected \"number_of_inputs\" to be 0 not {0}!".format(json["number_of_inputs"]))
else:
for n in range(json["number_of_inputs"]):
w = self.createInputWidget(n)
inputSelectorLabel = qt.QLabel("Input Volume: ")
self.widgets.append(inputSelectorLabel)
# add to layout after connection
parametersFormLayout.addRow(inputSelectorLabel, w)
self.inputs.append(w.currentNode())
#end for each input
if json["template_code_filename"] == "KernelImageFilter":
w = self.createVectorWidget("KernelRadius","std::vector<uint32_t>")
self.widgets.append(w)
self.addWidgetWithToolTipAndLabel(w,{"briefdescriptionSet":"Radius of structuring element","name":"KernelRadius"})
labels=["Annulus",
"Box",
"Ball",
"Cross"]
values=["sitk.sitkAnnulus",
"sitk.sitkBox",
"sitk.sitkBall",
"sitk.sitkCross"]
w = self.createEnumWidget("KernelType",labels,values)
self.addWidgetWithToolTipAndLabel(w,{"briefdescriptionSet":"Structuring element","name":"Kernel Type"})
elif json["template_code_filename"] == "RegionGrowingImageFilter"\
or json["template_code_filename"] == "FastMarchingImageFilter":
name="SeedList"
if (json["template_code_filename"] == "FastMarchingImageFilter"):
name="TrialPoints"
fiducialSelector = slicer.qMRMLNodeComboBox()
self.widgets.append(fiducialSelector)
fiducialSelector.nodeTypes = ( "vtkMRMLMarkupsFiducialNode", "vtkMRMLAnnotationHierarchyNode")
fiducialSelector.addAttribute("vtkMRMLAnnotationHierarchyNode", "MainChildType", "vtkMRMLAnnotationFiducialNode" )
fiducialSelector.selectNodeUponCreation = True
fiducialSelector.addEnabled = True
fiducialSelector.removeEnabled = False
fiducialSelector.renameEnabled = True
fiducialSelector.noneEnabled = False
fiducialSelector.showHidden = False
fiducialSelector.showChildNodeTypes = True
fiducialSelector.setMRMLScene( slicer.mrmlScene )
fiducialSelector.setToolTip( "Pick the Markups node for the seed list." )
fiducialSelector.connect("nodeActivated(vtkMRMLNode*)", lambda node,name=name:self.onFiducialListNode(name,node))
self.prerun_callbacks.append(lambda w=fiducialSelector,name=name:self.onFiducialListNode(name,w.currentNode()))
fiducialSelectorLabel = qt.QLabel("{0}: ".format(name))
self.widgets.append(fiducialSelectorLabel)
#todo set tool tip
# add to layout after connection
parametersFormLayout.addRow(fiducialSelectorLabel, fiducialSelector)
#
# Iterate over the members in the JSON to generate a GUI
#
for member in json["members"]:
w = None
if "type" in member:
t = member["type"]
if "dim_vec" in member and int(member["dim_vec"]):
if member["itk_type"].endswith("IndexType") or member["itk_type"].endswith("PointType"):
isPoint = member["itk_type"].endswith("PointType")
fiducialSelector = slicer.qMRMLNodeComboBox()
self.widgets.append(fiducialSelector)
fiducialSelector.nodeTypes = ( "vtkMRMLMarkupsFiducialNode", "vtkMRMLAnnotationFiducialNode" )
fiducialSelector.selectNodeUponCreation = True
fiducialSelector.addEnabled = False
fiducialSelector.removeEnabled = False
fiducialSelector.renameEnabled = True
fiducialSelector.noneEnabled = False
fiducialSelector.showHidden = False
fiducialSelector.showChildNodeTypes = True
fiducialSelector.setMRMLScene( slicer.mrmlScene )
fiducialSelector.setToolTip( "Pick the Fiducial for the Point or Index" )
fiducialSelector.connect("nodeActivated(vtkMRMLNode*)", lambda node,w=fiducialSelector,name=member["name"],isPt=isPoint:self.onFiducialNode(name,w,isPt))
self.prerun_callbacks.append(lambda w=fiducialSelector,name=member["name"],isPt=isPoint:self.onFiducialNode(name,w,isPt))
w1 = fiducialSelector
fiducialSelectorLabel = qt.QLabel("{0}: ".format(member["name"]))
self.widgets.append(fiducialSelectorLabel)
icon = qt.QIcon(SimpleFilters.ICON_DIR+"Fiducials.png")
toggle = qt.QPushButton(icon, "")
toggle.setCheckable(True)
toggle.toolTip = "Toggle Fiducial Selection"
self.widgets.append(toggle)
w2 = self.createVectorWidget(member["name"],t)
hlayout = qt.QHBoxLayout()
hlayout.addWidget(fiducialSelector)
hlayout.setStretchFactor(fiducialSelector,1)
hlayout.addWidget(w2)
hlayout.setStretchFactor(w2,1)
hlayout.addWidget(toggle)
hlayout.setStretchFactor(toggle,0)
w1.hide()
self.widgets.append(hlayout)
toggle.connect("clicked(bool)", lambda checked,ptW=w2,fidW=w1:self.onToggledPointSelector(checked,ptW,fidW))
parametersFormLayout.addRow(fiducialSelectorLabel, hlayout)
else:
w = self.createVectorWidget(member["name"],t)
elif "point_vec" in member:
fiducialSelector = slicer.qMRMLNodeComboBox()
self.widgets.append(fiducialSelector)
fiducialSelector.nodeTypes = ( "vtkMRMLMarkupsFiducialNode", "vtkMRMLAnnotationHierarchyNode")
fiducialSelector.addAttribute("vtkMRMLAnnotationHierarchyNode", "MainChildType", "vtkMRMLAnnotationFiducialNode" )
fiducialSelector.selectNodeUponCreation = True
fiducialSelector.addEnabled = True
fiducialSelector.removeEnabled = False
fiducialSelector.renameEnabled = True
fiducialSelector.noneEnabled = False
fiducialSelector.showHidden = False
fiducialSelector.showChildNodeTypes = True
fiducialSelector.setMRMLScene( slicer.mrmlScene )
fiducialSelector.setToolTip( "Pick the Markups node for the point list." )
fiducialSelector.connect("nodeActivated(vtkMRMLNode*)", lambda node,name=member["name"]:self.onFiducialListNode(name,node))
self.prerun_callbacks.append(lambda w=fiducialSelector,name=member["name"],:self.onFiducialListNode(name,w.currentNode()))
w = fiducialSelector
elif "enum" in member:
w = self.createEnumWidget(member["name"],member["enum"])
elif member["name"].endswith("Direction") and "std::vector" in t:
# This member name is use for direction cosine matrix for image sources.
# We are going to ignore it
pass
elif t == "InterpolatorEnum":
labels=["Nearest Neighbor",
"Linear",
"BSpline",
"Gaussian",
"Label Gaussian",
"Hamming Windowed Sinc",
"Cosine Windowed Sinc",
"Welch Windowed Sinc",
"Lanczos Windowed Sinc",
"Blackman Windowed Sinc"]
values=["sitk.sitkNearestNeighbor",
"sitk.sitkLinear",
"sitk.sitkBSpline",
"sitk.sitkGaussian",
"sitk.sitkLabelGaussian",
"sitk.sitkHammingWindowedSinc",
"sitk.sitkCosineWindowedSinc",
"sitk.sitkWelchWindowedSinc",
"sitk.sitkLanczosWindowedSinc",
"sitk.sitkBlackmanWindowedSinc"]
w = self.createEnumWidget(member["name"],labels,values)
pass
elif t == "PixelIDValueEnum":
labels=["int8_t",
"uint8_t",
"int16_t",
"uint16_t",
"uint32_t",
"int32_t",
"float",
"double"]
values=["sitk.sitkInt8",
"sitk.sitkUInt8",
"sitk.sitkInt16",
"sitk.sitkUInt16",
"sitk.sitkInt32",
"sitk.sitkUInt32",
"sitk.sitkFloat32",
"sitk.sitkFloat64"]
w = self.createEnumWidget(member["name"],labels,values)
elif t in ["double", "float"]:
w = self.createDoubleWidget(member["name"])
elif t == "bool":
w = self.createBoolWidget(member["name"])
elif t in ["uint8_t", "int8_t",
"uint16_t", "int16_t",
"uint32_t", "int32_t",
"uint64_t", "int64_t",
"unsigned int", "int"]:
w = self.createIntWidget(member["name"],t)
else:
import sys
sys.stderr.write("Unknown member \"{0}\" of type \"{1}\"\n".format(member["name"],member["type"]))
if w:
self.addWidgetWithToolTipAndLabel(w,member)
# end for each member
#
# output volume selector
#
outputSelectorLabel = qt.QLabel("Output Volume: ")
self.widgets.append(outputSelectorLabel)
self.outputSelector = slicer.qMRMLNodeComboBox()
self.widgets.append(self.outputSelector)
self.outputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode", "vtkMRMLLabelMapVolumeNode"]
self.outputSelector.selectNodeUponCreation = True
self.outputSelector.addEnabled = True
self.outputSelector.removeEnabled = False
self.outputSelector.renameEnabled = True
self.outputSelector.noneEnabled = False
self.outputSelector.showHidden = False
self.outputSelector.showChildNodeTypes = False
self.outputSelector.baseName = json["name"]+" Output"
self.outputSelector.setMRMLScene( slicer.mrmlScene )
self.outputSelector.setToolTip( "Pick the output to the algorithm." )
self.outputSelector.connect("nodeActivated(vtkMRMLNode*)", lambda node:self.onOutputSelect(node))
# add to layout after connection
parametersFormLayout.addRow(outputSelectorLabel, self.outputSelector)
self.output = self.outputSelector.currentNode()
#
# LabelMap toggle
#
outputLabelMapLabel = qt.QLabel("LabelMap: ")
self.widgets.append(outputLabelMapLabel)
self.outputLabelMapBox = qt.QCheckBox()
self.widgets.append(self.outputLabelMapBox)
self.outputLabelMapBox.setToolTip("Output Volume is set as a labelmap")
self.outputLabelMapBox.setChecked(self.outputLabelMap)
self.outputLabelMapBox.setDisabled(True)
self.outputLabelMapBox.connect("stateChanged(int)", lambda val:self.onOutputLabelMapChanged(bool(val)))
# add to layout after connection
parametersFormLayout.addRow(outputLabelMapLabel, self.outputLabelMapBox)
def createInputWidget(self,n, noneEnabled=False):
inputSelector = slicer.qMRMLNodeComboBox()
self.widgets.append(inputSelector)
inputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode", "vtkMRMLLabelMapVolumeNode"]
inputSelector.selectNodeUponCreation = True
inputSelector.addEnabled = False
inputSelector.removeEnabled = False
inputSelector.noneEnabled = noneEnabled
inputSelector.showHidden = False
inputSelector.showChildNodeTypes = False
inputSelector.setMRMLScene( slicer.mrmlScene )
inputSelector.setToolTip( "Pick the input to the algorithm." )
# connect and verify parameters
inputSelector.connect("nodeActivated(vtkMRMLNode*)", lambda node,i=n:self.onInputSelect(node,i))
return inputSelector
def createEnumWidget(self,name,enumList,valueList=None):
w = qt.QComboBox()
self.widgets.append(w)
exec 'default=self.filter.Get{0}()'.format(name) in globals(), locals()
if valueList is None:
valueList = ["self.filter."+e for e in enumList]
for e,v in zip(enumList,valueList):
w.addItem(e,v)
# check if current item is default, set if it is
exec 'itemValue='+v in globals(), locals()
if itemValue == default:
w.setCurrentIndex(w.count-1)
w.connect("currentIndexChanged(int)", lambda selectorIndex,n=name,selector=w:self.onEnumChanged(n,selectorIndex,selector))
return w
def createVectorWidget(self,name,type):
m = re.search(r"<([a-zA-Z ]+)>", type)
if m:
type = m.group(1)
w = ctk.ctkCoordinatesWidget()
self.widgets.append(w)
if type in ["double", "float"]:
w.setDecimals(5)
w.minimum=-3.40282e+038
w.maximum=3.40282e+038
w.connect("coordinatesChanged(double*)", lambda val,widget=w,name=name:self.onFloatVectorChanged(name,widget,val))
elif type == "bool":
w.setDecimals(0)
w.minimum=0
w.maximum=1
w.connect("coordinatesChanged(double*)", lambda val,widget=w,name=name:self.onBoolVectorChanged(name,widget,val))
else:
w.setDecimals(0)
w.connect("coordinatesChanged(double*)", lambda val,widget=w,name=name:self.onIntVectorChanged(name,widget,val))
exec('default = self.filter.Get{0}()'.format(name)) in globals(), locals()
w.coordinates = ",".join(str(x) for x in default)
return w
def createIntWidget(self,name,type="int"):
w = qt.QSpinBox()
self.widgets.append(w)
if type=="uint8_t":
w.setRange(0,255)
elif type=="int8_t":
w.setRange(-128,127)
elif type=="uint16_t":
w.setRange(0,65535)
elif type=="int16_t":
w.setRange(-32678,32767)
elif type=="uint32_t" or type=="uint64_t" or type=="unsigned int":
w.setRange(0,2147483647)
elif type=="int32_t" or type=="uint64_t" or type=="int":
w.setRange(-2147483648,2147483647)
exec('default = self.filter.Get{0}()'.format(name)) in globals(), locals()
w.setValue(int(default))
w.connect("valueChanged(int)", lambda val,name=name:self.onScalarChanged(name,val))
return w
def createBoolWidget(self,name):
exec('default = self.filter.Get{0}()'.format(name)) in globals(), locals()
w = qt.QCheckBox()
self.widgets.append(w)
w.setChecked(default)
w.connect("stateChanged(int)", lambda val,name=name:self.onScalarChanged(name,bool(val)))
return w
def createDoubleWidget(self,name):
exec('default = self.filter.Get{0}()'.format(name)) in globals(), locals()
w = qt.QDoubleSpinBox()
self.widgets.append(w)
w.setRange(-3.40282e+038, 3.40282e+038)
w.decimals = 5
w.setValue(default)
w.connect("valueChanged(double)", lambda val,name=name:self.onScalarChanged(name,val))
return w
def addWidgetWithToolTipAndLabel(self,widget,memberJSON):
tip=""
if "briefdescriptionSet" in memberJSON and len(memberJSON["briefdescriptionSet"]):
tip=memberJSON["briefdescriptionSet"]
elif "detaileddescriptionSet" in memberJSON:
tip=memberJSON["detaileddescriptionSet"]
# remove trailing white space
tip=tip.rstrip()
l = qt.QLabel(self.BeautifyCamelCase(memberJSON["name"])+": ")
self.widgets.append(l)
widget.setToolTip(tip)
l.setToolTip(tip)
parametersFormLayout = self.parent.layout()
parametersFormLayout.addRow(l,widget)
def onToggledPointSelector(self, fidVisible, ptWidget, fiducialWidget):
ptWidget.setVisible(False)
fiducialWidget.setVisible(False)
ptWidget.setVisible(not fidVisible)
fiducialWidget.setVisible(fidVisible)
if ptWidget.visible:
# Update the coordinate values to envoke the changed signal.
# This will update the filter from the widget