forked from QIICR/QuantitativeReporting
/
DICOMSurfaceSegmentationPlugin.py
604 lines (478 loc) · 25.8 KB
/
DICOMSurfaceSegmentationPlugin.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
import glob, os, json
from datetime import datetime
import string
import vtk, qt, ctk, slicer
from DICOMLib import DICOMPlugin
from DICOMLib import DICOMLoadable
import logging
#
# This is the plugin to handle translation of DICOM Surface SEG objects
#
class DICOMSurfaceSegmentationPluginClass(DICOMPlugin):
def __init__(self,epsilon=0.01):
super(DICOMSurfaceSegmentationPluginClass,self).__init__()
self.loadType = "DICOMSurfaceSegmentation"
self.surfaceSegmentationSOPClassUID = "1.2.840.10008.5.1.4.1.1.66.5"
self.tags['seriesInstanceUID'] = "0020,000E"
self.tags['seriesDescription'] = "0008,103E"
self.tags['seriesNumber'] = "0020,0011"
self.tags['modality'] = "0008,0060"
self.tags['sopClassUID'] = "0008,0016"
self.tags['instanceUID'] = "0008,0018"
def examine(self,fileLists):
""" Returns a list of DICOMLoadable instances
corresponding to ways of interpreting the
fileLists parameter.
"""
loadables = []
for files in fileLists:
loadables += self.examineFiles(files)
return loadables
def examineFiles(self,files):
""" Returns a list of DICOMLoadable instances
corresponding to ways of interpreting the
files parameter.
"""
loadables = []
# just read the modality type; need to go to reporting logic, since DCMTK
# is not wrapped ...
for cFile in files:
uid = slicer.dicomDatabase.fileValue(cFile, self.tags['instanceUID'])
if uid == '':
return []
desc = slicer.dicomDatabase.fileValue(cFile, self.tags['seriesDescription'])
if desc == '':
desc = "Unknown"
number = slicer.dicomDatabase.fileValue(cFile, self.tags['seriesNumber'])
if number == '':
number = "Unknown"
isSurfaceSeg = (slicer.dicomDatabase.fileValue(cFile, self.tags['sopClassUID']) == self.surfaceSegmentationSOPClassUID)
if isSurfaceSeg:
loadable = DICOMLoadable()
loadable.files = [cFile]
loadable.name = desc + ' - as a DICOM Surface SEG object'
loadable.tooltip = loadable.name
loadable.selected = True
loadable.confidence = 0.99
loadable.uid = uid
self.addReferences(loadable)
refName = self.referencedSeriesName(loadable)
if refName != "":
loadable.name = refName + " " + desc + " - SurfaceSegmentations"
loadables.append(loadable)
print('DICOM Surface SEG found')
return loadables
def referencedSeriesName(self,loadable):
"""Returns the default series name for the given loadable"""
referencedName = "Unnamed Reference"
if hasattr(loadable, "referencedSeriesUID"):
referencedName = self.defaultSeriesNodeName(loadable.referencedSeriesUID)
return referencedName
def addReferences(self,loadable):
"""Puts a list of the referenced UID into the loadable for use
in the node if this is loaded."""
import dicom
dcm = dicom.read_file(loadable.files[0])
if hasattr(dcm, "ReferencedSeriesSequence"):
# look up all of the instances in the series, since segmentation frames
# may be non-contiguous
if hasattr(dcm.ReferencedSeriesSequence[0], "SeriesInstanceUID"):
loadable.referencedInstanceUIDs = []
for f in slicer.dicomDatabase.filesForSeries(dcm.ReferencedSeriesSequence[0].SeriesInstanceUID):
refDCM = dicom.read_file(f)
# this is a hack that should probably fixed in Slicer core - not all
# of those instances are truly referenced!
loadable.referencedInstanceUIDs.append(refDCM.SOPInstanceUID)
loadable.referencedSeriesUID = dcm.ReferencedSeriesSequence[0].SeriesInstanceUID
def getValuesFromCodeSequence(self, segment, codeSequenceName, defaults=None):
try:
cs = segment[codeSequenceName]
return cs["CodeValue"], cs["CodingSchemeDesignator"], cs["CodeMeaning"]
except KeyError:
return defaults if defaults else ['', '', '']
def load(self,loadable):
""" Load the DICOM SEG object
"""
print('DICOM SEG load()')
try:
uid = loadable.uid
print ('in load(): uid = ', uid)
except AttributeError:
return False
import dicom
dataset = dicom.read_file(loadable.files[0])
self.loadSurfaceSegmentationDataset(dataset)
def loadSurfaceSegmentationDataset(self,dataset):
"""For testing:
import dicom
execfile('/Users/pieper/slicer4/latest/ExtensionsIndex-build/QuantitativeReporting/Py/DICOMSurfaceSegmentationPlugin.py')
dataset = dicom.read_file('/Users/pieper/data/surface-seg/data/Series 001 [SEG - ProFuse segmentation of prostate]/1.3.6.1.4.1.30323.273440548164167.20160909.162908090.dcm')
segPlugin = DICOMSurfaceSegmentationPluginClass()
segPlugin.loadSurfaceSegmentationDataset(dataset)
"""
for surface in dataset.SurfaceSequence:
coordinates = surface.SurfacePointsSequence[0].PointCoordinatesData
slicer.modules.coordinates = coordinates
scene = slicer.mrmlScene
points = vtk.vtkPoints()
polyData = vtk.vtkPolyData()
polyData.SetPoints(points)
for pointIndex in xrange(len(coordinates)/3):
pointStart = pointIndex*3
point = coordinates[pointStart:pointStart+3]
point[0] *= -1
point[1] *= -1
points.InsertNextPoint(*point)
polys = vtk.vtkCellArray()
polyData.SetPolys(polys)
extremes = [100,1]
triIndices = surface.SurfaceMeshPrimitivesSequence[0].TrianglePointIndexList
triangles = len(triIndices)/6
for triangle in range(triangles):
polys.InsertNextCell(3)
for vertex in range(3):
vertexIndex = 6*triangle + 2*vertex;
low = ord(triIndices[vertexIndex])
high = ord(triIndices[vertexIndex+1])
index = (high << 8) + low
#print(low, high, index)
polys.InsertCellPoint(index)
if index < extremes[0]:
extremes[0] = index
if index > extremes[1]:
extremes[1] = index
print(extremes, len(coordinates)/3.)
# Create model node
model = slicer.vtkMRMLModelNode()
model.SetScene(scene)
model.SetName(scene.GenerateUniqueName("Segment-%d" % surface.SurfaceNumber))
model.SetAndObservePolyData(polyData)
# Create display node
modelDisplay = slicer.vtkMRMLModelDisplayNode()
genericAnatomy = slicer.util.getNode('GenericAnatomyColors')
color = [0,]*3
genericAnatomy.GetLookupTable().GetColor(surface.SurfaceNumber, color)
modelDisplay.SetColor(*color)
modelDisplay.SetScene(scene)
scene.AddNode(modelDisplay)
model.SetAndObserveDisplayNodeID(modelDisplay.GetID())
scene.AddNode(model)
return True
comment = '''
# Load terminology in the metafile into context
terminologiesLogic = slicer.modules.terminologies.logic()
terminologiesLogic.LoadTerminologyFromSurfaceSegmentDescriptorFile(loadable.name, metaFileName)
terminologiesLogic.LoadAnatomicContextFromSurfaceSegmentDescriptorFile(loadable.name, metaFileName)
with open(metaFileName) as metaFile:
data = json.load(metaFile)
logging.debug('number of segmentation files = ' + str(numberOfSurfaceSegments))
if numberOfSurfaceSegments != len(data["segmentAttributes"]):
logging.error('Loading failed: Inconsistent number of segments in the descriptor file and on disk')
return
for segmentAttributes in data["segmentAttributes"]:
# TODO: only handles the first item of lists
for segment in segmentAttributes:
# load each of the segments' segmentations
# Initialize color and terminology from .info file
# See SEG2NRRD.cxx and EncodeSEG.cxx for how it's written.
# Format of the .info file (no leading spaces, labelNum, RGBColor, SegmentedPropertyCategory and
# SegmentedPropertyCategory are required):
# labelNum;RGB:R,G,B;SegmentedPropertyCategory:code,scheme,meaning;SegmentedPropertyType:code,scheme,meaning;SegmentedPropertyTypeModifier:code,scheme,meaning;AnatomicRegion:code,scheme,meaning;AnatomicRegionModifier:code,scheme,meaning
# R, G, B are 0-255 in file, but mapped to 0-1 for use in color node
# set defaults in case of missing fields, modifiers are optional
try:
rgb255 = segment["recommendedDisplayRGBValue"]
rgb = map(lambda c: float(c) / 255., rgb255)
except KeyError:
rgb = (0., 0., 0.)
segmentId = segment["LabelID"]
defaults = ['T-D0050', 'Tissue', 'SRT']
categoryCode, categoryCodingScheme, categoryCodeMeaning = \
self.getValuesFromCodeSequence(segment, "SegmentedPropertyCategoryCodeSequence", defaults)
typeCode, typeCodingScheme, typeCodeMeaning = \
self.getValuesFromCodeSequence(segment, "SegmentedPropertyTypeCodeSequence", defaults)
typeModCode, typeModCodingScheme, typeModCodeMeaning = \
self.getValuesFromCodeSequence(segment, "SegmentedPropertyTypeModifierCodeSequence")
anatomicRegionDefaults = ['T-D0010', 'SRT', 'Entire Body']
regionCode, regionCodingScheme, regionCodeMeaning = \
self.getValuesFromCodeSequence(segment, "AnatomicRegionCodeSequence", anatomicRegionDefaults)
regionModCode, regionModCodingScheme, regionModCodeMeaning = \
self.getValuesFromCodeSequence(segment, "AnatomicRegionModifierCodeSequence")
dummyTerminologyWidget = slicer.qSlicerTerminologyNavigatorWidget() # Still cannot call static methods from python
segmentTerminologyTag = dummyTerminologyWidget.serializeTerminologyEntry(
loadable.name,
categoryCode, categoryCodingScheme, categoryCodeMeaning,
typeCode, typeCodingScheme, typeCodeMeaning,
typeModCode, typeModCodingScheme, typeModCodeMeaning,
loadable.name,
regionCode, regionCodingScheme, regionCodeMeaning,
regionModCode, regionModCodingScheme, regionModCodeMeaning)
# end of processing a line of terminology
# TODO: Create logic class that both CLI and this plugin uses so that we don't need to have temporary NRRD files and labelmap nodes
# if not hasattr(slicer.modules, 'segmentations'):
# load the segmentation volume file and name it for the reference series and segment color
labelFileName = os.path.join(outputDir, str(segmentId) + ".nrrd")
segmentName = seriesName + "-" + typeCodeMeaning + "-label"
(success, labelNode) = slicer.util.loadLabelVolume(labelFileName,
properties={'name': segmentName},
returnNode=True)
if not success:
raise ValueError("{} could not be loaded into Slicer!".format(labelFileName))
segmentLabelNodes.append(labelNode)
# Set terminology properties as attributes to the label node (which is a temporary node)
#TODO: This is a quick solution, maybe there is a better one
labelNode.SetAttribute("Terminology", segmentTerminologyTag)
labelNode.SetAttribute("ColorR", str(rgb[0]))
labelNode.SetAttribute("ColorG", str(rgb[1]))
labelNode.SetAttribute("ColorB", str(rgb[2]))
# TODO: initialize referenced UID (and segment number?) attribute(s)
# dataset = dicom.read_file(segFileName)
# referencedSeries = dict()
# for refSeriesItem in dataset.ReferencedSeriesSequence:
# refSOPInstanceUIDs = []
# for refSOPInstanceItem in refSeriesItem.ReferencedInstanceSequence:
# refSOPInstanceUIDs.append(refSOPInstanceItem.ReferencedSOPInstanceUID)
# referencedSeries[refSeriesItem.SeriesInstanceUID] = refSOPInstanceUIDs
# segmentationNode.SetAttribute("DICOM.referencedInstanceUIDs", str(referencedSeries))
# create Subject hierarchy nodes for the loaded series
self.addSeriesInSubjectHierarchy(loadable, labelNode)
metaFile.close()
# TODO: the outputDir should be cleaned up
import vtkSegmentationCorePython as vtkSegmentationCore
segmentationNode = slicer.vtkMRMLSegmentationNode()
segmentationNode.SetName(seriesName)
slicer.mrmlScene.AddNode(segmentationNode)
segmentationDisplayNode = slicer.vtkMRMLSegmentationDisplayNode()
slicer.mrmlScene.AddNode(segmentationDisplayNode)
segmentationNode.SetAndObserveDisplayNodeID(segmentationDisplayNode.GetID())
segmentation = vtkSegmentationCore.vtkSegmentation()
segmentation.SetMasterRepresentationName(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName())
segmentationNode.SetAndObserveSegmentation(segmentation)
self.addSeriesInSubjectHierarchy(loadable, segmentationNode)
for segmentLabelNode in segmentLabelNodes:
segment = vtkSegmentationCore.vtkSegment()
segment.SetName(segmentLabelNode.GetName())
segmentColor = [float(segmentLabelNode.GetAttribute("ColorR")), float(segmentLabelNode.GetAttribute("ColorG")), float(segmentLabelNode.GetAttribute("ColorB"))]
segment.SetDefaultColor(segmentColor)
segment.SetTag(vtkSegmentationCore.vtkSegment.GetTerminologyEntryTagName(), segmentLabelNode.GetAttribute("Terminology"))
#TODO: when the logic class is created, this will need to be changed
orientedImage = slicer.vtkSlicerSegmentationsModuleLogic.CreateOrientedImageDataFromVolumeNode(segmentLabelNode)
segment.AddRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName(), orientedImage)
segmentation.AddSegment(segment)
segmentDisplayNode = segmentLabelNode.GetDisplayNode()
if segmentDisplayNode is not None:
slicer.mrmlScene.RemoveNode(segmentDisplayNode)
slicer.mrmlScene.RemoveNode(segmentLabelNode)
segmentation.CreateRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationClosedSurfaceRepresentationName(), True)
'''
return True
def examineForExport(self, node):
exportable = None
if node.GetAssociatedNode() and node.GetAssociatedNode().IsA('vtkMRMLSegmentationNode'):
# Check to make sure all referenced UIDs exist in the database.
instanceUIDs = node.GetAttribute("DICOM.ReferencedInstanceUIDs").split()
if instanceUIDs == "":
return []
for instanceUID in instanceUIDs:
inputDICOMImageFileName = slicer.dicomDatabase.fileForInstance(instanceUID)
if inputDICOMImageFileName == "":
return []
exportable = slicer.qSlicerDICOMExportable()
exportable.confidence = 1.0
exportable.setTag('Modality', 'SEG')
if exportable is not None:
exportable.name = self.loadType
exportable.tooltip = "Create DICOM files from segmentation"
exportable.nodeID = node.GetID()
exportable.pluginClass = self.__module__
# Define common required tags and default values
exportable.setTag('SeriesDescription', 'No series description')
exportable.setTag('SeriesNumber', '1')
return [exportable]
return []
def export(self, exportables):
exportablesCollection = vtk.vtkCollection()
for exportable in exportables:
vtkExportable = slicer.vtkSlicerDICOMExportable()
exportable.copyToVtkExportable(vtkExportable)
exportablesCollection.AddItem(vtkExportable)
self.exportAsDICOMSEG(exportablesCollection)
def exportAsDICOMSEG(self, exportablesCollection):
"""Export the given node to a segmentation object and load it in the
DICOM database
This function was copied and modified from the EditUtil.py function of the same name in Slicer.
"""
import logging
if hasattr(slicer.modules, 'segmentations'):
exportable = exportablesCollection.GetItemAsObject(0)
subjectHierarchyNode = slicer.mrmlScene.GetNodeByID(exportable.GetNodeID())
instanceUIDs = subjectHierarchyNode.GetAttribute("DICOM.ReferencedInstanceUIDs").split()
if instanceUIDs == "":
raise Exception("Editor master node does not have DICOM information")
# get the list of source DICOM files
inputDICOMImageFileNames = ""
for instanceUID in instanceUIDs:
inputDICOMImageFileNames += slicer.dicomDatabase.fileForInstance(instanceUID) + ","
inputDICOMImageFileNames = inputDICOMImageFileNames[:-1] # strip last comma
# save the per-structure volumes in the temp directory
inputSurfaceSegmentationsFileNames = ""
import random # TODO: better way to generate temp file names?
import vtkITK
writer = vtkITK.vtkITKImageWriter()
rasToIJKMatrix = vtk.vtkMatrix4x4()
import vtkSegmentationCore
import vtkSlicerSegmentationsModuleLogic
logic = vtkSlicerSegmentationsModuleLogic.vtkSlicerSegmentationsModuleLogic()
segmentationNode = subjectHierarchyNode.GetAssociatedNode()
mergedSegmentationImageData = segmentationNode.GetImageData()
mergedSegmentationLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode()
segmentationNode.GetRASToIJKMatrix(rasToIJKMatrix)
mergedSegmentationLabelmapNode.SetRASToIJKMatrix(rasToIJKMatrix)
mergedSegmentationLabelmapNode.SetAndObserveImageData(mergedSegmentationImageData)
mergedSegmentationOrientedImageData = logic.CreateOrientedImageDataFromVolumeNode(mergedSegmentationLabelmapNode)
segmentation = segmentationNode.GetSegmentation()
segmentIDs = vtk.vtkStringArray()
segmentation.GetSegmentIDs(segmentIDs)
segmentationName = segmentationNode.GetName()
for i in range(0, segmentIDs.GetNumberOfValues()):
segmentID = segmentIDs.GetValue(i)
segment = segmentation.GetSegment(segmentID)
segmentName = segment.GetName()
structureName = segmentName[len(segmentationName)+1:-1*len('-label')]
structureFileName = structureName + str(random.randint(0,vtk.VTK_INT_MAX)) + ".nrrd"
filePath = os.path.join(slicer.app.temporaryPath, structureFileName)
writer.SetFileName(filePath)
segmentImageData = segment.GetRepresentation(vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationBinaryLabelmapRepresentationName())
paddedImageData = vtkSegmentationCore.vtkOrientedImageData()
vtkSegmentationCore.vtkOrientedImageDataResample.PadImageToContainImage(segmentImageData, mergedSegmentationOrientedImageData, paddedImageData)
labelmapImageData = slicer.vtkMRMLLabelMapVolumeNode()
logic.CreateLabelmapVolumeFromOrientedImageData(paddedImageData, labelmapImageData)
writer.SetInputDataObject(labelmapImageData.GetImageData())
labelmapImageData.GetRASToIJKMatrix(rasToIJKMatrix)
writer.SetRasToIJKMatrix(rasToIJKMatrix)
logging.debug("Saving to %s..." % filePath)
writer.Write()
inputSegmentationsFileNames += filePath + ","
inputSegmentationsFileNames = inputSegmentationsFileNames[:-1] # strip last comma
# save the per-structure volumes label attributes
colorNode = segmentationNode.GetNodeReference('colorNodeID')
terminologyName = colorNode.GetAttribute("TerminologyName")
colorLogic = slicer.modules.colors.logic()
if not terminologyName or not colorLogic:
raise Exception("No terminology or color logic - cannot export")
inputLabelAttributesFileNames = ""
for i in range(0, segmentIDs.GetNumberOfValues()):
segmentID = segmentIDs.GetValue(i)
segment = segmentation.GetSegment(segmentID)
segmentName = segment.GetName()
structureName = segmentName[len(segmentationName)+1:-1*len('-label')]
labelIndex = colorNode.GetColorIndexByName( structureName )
rgbColor = [0,]*4
colorNode.GetColor(labelIndex, rgbColor)
rgbColor = map(lambda e: e*255., rgbColor)
# get the attributes and convert to format CodeValue,CodeMeaning,CodingSchemeDesignator
# or empty strings if not defined
propertyCategoryWithColons = colorLogic.GetSegmentedPropertyCategory(labelIndex, terminologyName)
if propertyCategoryWithColons == '':
logging.debug ('ERROR: no segmented property category found for label ',str(labelIndex))
# Try setting a default as this section is required
propertyCategory = "C94970,NCIt,Reference Region"
else:
propertyCategory = propertyCategoryWithColons.replace(':',',')
propertyTypeWithColons = colorLogic.GetSegmentedPropertyType(labelIndex, terminologyName)
propertyType = propertyTypeWithColons.replace(':',',')
propertyTypeModifierWithColons = colorLogic.GetSegmentedPropertyTypeModifier(labelIndex, terminologyName)
propertyTypeModifier = propertyTypeModifierWithColons.replace(':',',')
anatomicRegionWithColons = colorLogic.GetAnatomicRegion(labelIndex, terminologyName)
anatomicRegion = anatomicRegionWithColons.replace(':',',')
anatomicRegionModifierWithColons = colorLogic.GetAnatomicRegionModifier(labelIndex, terminologyName)
anatomicRegionModifier = anatomicRegionModifierWithColons.replace(':',',')
structureFileName = structureName + str(random.randint(0,vtk.VTK_INT_MAX)) + ".info"
filePath = os.path.join(slicer.app.temporaryPath, structureFileName)
# EncodeSEG is expecting a file of format:
# labelNum;SegmentedPropertyCategory:codeValue,codeScheme,codeMeaning;SegmentedPropertyType:v,m,s etc
attributes = "%d" % labelIndex
attributes += ";SegmentedPropertyCategory:"+propertyCategory
if propertyType != "":
attributes += ";SegmentedPropertyType:" + propertyType
if propertyTypeModifier != "":
attributes += ";SegmentedPropertyTypeModifier:" + propertyTypeModifier
if anatomicRegion != "":
attributes += ";AnatomicRegion:" + anatomicRegion
if anatomicRegionModifier != "":
attributes += ";AnatomicRegionModifier:" + anatomicRegionModifier
attributes += ";SegmentAlgorithmType:AUTOMATIC"
attributes += ";SegmentAlgorithmName:SlicerSelfTest"
attributes += ";RecommendedDisplayRGBValue:%g,%g,%g" % tuple(rgbColor[:-1])
fp = open(filePath, "w")
fp.write(attributes)
fp.close()
logging.debug ("filePath: %s", filePath)
logging.debug ("attributes: %s", attributes)
inputLabelAttributesFileNames += filePath + ","
inputLabelAttributesFileNames = inputLabelAttributesFileNames[:-1] # strip last comma'''
try:
user = os.environ['USER']
except KeyError:
user = "Unspecified"
segFileName = "editor_export.SEG" + str(random.randint(0,vtk.VTK_INT_MAX)) + ".dcm"
segFilePath = os.path.join(slicer.app.temporaryPath, segFileName)
# TODO: define a way to set parameters like description
# TODO: determine a good series number automatically by looking in the database
parameters = {
"inputDICOMImageFileNames": inputDICOMImageFileNames,
"inputSegmentationsFileNames": inputSegmentationsFileNames,
"inputLabelAttributesFileNames": inputLabelAttributesFileNames,
"readerId": user,
"sessionId": "1",
"timePointId": "1",
"seriesDescription": "SlicerEditorSEGExport",
"seriesNumber": "100",
"instanceNumber": "1",
"bodyPart": "HEAD",
"algorithmDescriptionFileName": "Editor",
"outputSEGFileName": segFilePath,
"skipEmptySlices": False,
"compress": False,
}
encodeSEG = slicer.modules.encodeseg
cliNode = None
cliNode = slicer.cli.run(encodeSEG, cliNode, parameters, delete_temporary_files=False)
waitCount = 0
while cliNode.IsBusy() and waitCount < 20:
slicer.util.delayDisplay( "Running SEG Encoding... %d" % waitCount, 1000 )
waitCount += 1
if cliNode.GetStatusString() != 'Completed':
raise Exception("encodeSEG CLI did not complete cleanly")
logging.info("Added segmentation to DICOM database (%s)", segFilePath)
slicer.dicomDatabase.insert(segFilePath)
#
# DICOMSurfaceSegmentationPlugin
#
class DICOMSurfaceSegmentationPlugin:
"""
This class is the 'hook' for slicer to detect and recognize the plugin
as a loadable scripted module
"""
def __init__(self, parent):
parent.title = "DICOM SurfaceSegmentation Object Import Plugin"
parent.categories = ["Developer Tools.DICOM Plugins"]
parent.contributors = ["Andrey Fedorov, BWH"]
parent.helpText = """
Plugin to the DICOM Module to parse and load DICOM SEG modality.
No module interface here, only in the DICOM module
"""
parent.dependencies = ['DICOM', 'Colors']
parent.acknowledgementText = """
This DICOM Plugin was developed by
Andrey Fedorov, BWH.
and was partially funded by NIH grant U01CA151261.
"""
# Add this extension to the DICOM module's list for discovery when the module
# is created. Since this module may be discovered before DICOM itself,
# create the list if it doesn't already exist.
try:
slicer.modules.dicomPlugins
except AttributeError:
slicer.modules.dicomPlugins = {}
slicer.modules.dicomPlugins['DICOMSurfaceSegmentationPlugin'] = DICOMSurfaceSegmentationPluginClass