forked from Slicer/SlicerGitSVNArchive
-
Notifications
You must be signed in to change notification settings - Fork 2
/
vtkMRMLSegmentationNode.cxx
1219 lines (1098 loc) · 46.6 KB
/
vtkMRMLSegmentationNode.cxx
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
/*==============================================================================
Copyright (c) Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file was originally developed by Csaba Pinter, PerkLab, Queen's University
and was supported through the Applied Cancer Research Unit program of Cancer Care
Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care
==============================================================================*/
// Segmentations includes
#include "vtkMRMLSegmentationNode.h"
#include "vtkMRMLSegmentationDisplayNode.h"
#include "vtkMRMLSegmentationStorageNode.h"
// SegmentationCore includes
#include "vtkOrientedImageData.h"
#include "vtkOrientedImageDataResample.h"
#include "vtkCalculateOversamplingFactor.h"
// MRML includes
#include <vtkEventBroker.h>
#include <vtkMRMLScene.h>
#include <vtkMRMLTransformNode.h>
#include <vtkMRMLStorageNode.h>
#include <vtkMRMLSubjectHierarchyNode.h>
#include <vtkMRMLScalarVolumeNode.h>
// VTK includes
#include <vtkBoundingBox.h>
#include <vtkCallbackCommand.h>
#include <vtkGeneralTransform.h>
#include <vtkHomogeneousTransform.h>
#include <vtkImageThreshold.h>
#include <vtkIntArray.h>
#include <vtkLookupTable.h>
#include <vtkMath.h>
#include <vtkNew.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkSmartPointer.h>
#include <vtkStringArray.h>
#include <vtkMatrix4x4.h>
#include <vtkTransform.h>
// vtkITK includes
#include <vtkITKIslandMath.h>
// STD includes
#include <algorithm>
//----------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSegmentationNode);
//----------------------------------------------------------------------------
vtkMRMLSegmentationNode::vtkMRMLSegmentationNode()
{
this->SegmentationModifiedCallbackCommand = vtkSmartPointer<vtkCallbackCommand>::New();
this->SegmentationModifiedCallbackCommand->SetClientData(reinterpret_cast<void *>(this));
this->SegmentationModifiedCallbackCommand->SetCallback(vtkMRMLSegmentationNode::SegmentationModifiedCallback);
this->SegmentCenterTmp[0] = 0.0;
this->SegmentCenterTmp[1] = 0.0;
this->SegmentCenterTmp[2] = 0.0;
this->SegmentCenterTmp[3] = 1.0;
this->SegmentListFilterEnabled = false;
// Create empty segmentations object
this->Segmentation = nullptr;
vtkSmartPointer<vtkSegmentation> segmentation = vtkSmartPointer<vtkSegmentation>::New();
this->SetAndObserveSegmentation(segmentation);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::MasterRepresentationModified);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::ContainedRepresentationNamesModified);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::SegmentAdded);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::SegmentRemoved);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::SegmentModified);
this->ContentModifiedEvents->InsertNextValue(vtkSegmentation::SegmentsOrderModified);
this->AddNodeReferenceRole(this->GetLabelmapConversionColorTableNodeReferenceRole(),
this->GetLabelmapConversionColorTableNodeReferenceMRMLAttributeName());
}
//----------------------------------------------------------------------------
vtkMRMLSegmentationNode::~vtkMRMLSegmentationNode()
{
this->SetAndObserveSegmentation(nullptr);
// Make sure this callback cannot call this object
this->SegmentationModifiedCallbackCommand->SetClientData(nullptr);
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::WriteXML(ostream& of, int nIndent)
{
Superclass::WriteXML(of, nIndent);
if (this->Segmentation)
{
this->Segmentation->WriteXML(of, nIndent);
}
vtkMRMLWriteXMLBeginMacro(of);
vtkMRMLWriteXMLBooleanMacro(segmentListFilterEnabled, SegmentListFilterEnabled);
vtkMRMLWriteXMLStdStringMacro(segmentListFilterOptions, SegmentListFilterOptions);
vtkMRMLWriteXMLEndMacro();
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::ReadXMLAttributes(const char** atts)
{
// Read all MRML node attributes from two arrays of names and values
int disabledModify = this->StartModify();
Superclass::ReadXMLAttributes(atts);
if (!this->Segmentation)
{
vtkSmartPointer<vtkSegmentation> segmentation = vtkSmartPointer<vtkSegmentation>::New();
this->SetAndObserveSegmentation(segmentation);
}
this->Segmentation->ReadXMLAttributes(atts);
vtkMRMLReadXMLBeginMacro(atts);
vtkMRMLReadXMLBooleanMacro(segmentListFilterEnabled, SegmentListFilterEnabled);
vtkMRMLReadXMLStdStringMacro(segmentListFilterOptions, SegmentListFilterOptions);
vtkMRMLReadXMLEndMacro();
this->EndModify(disabledModify);
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::CopyContent(vtkMRMLNode* anode, bool deepCopy/*=true*/)
{
MRMLNodeModifyBlocker blocker(this);
Superclass::CopyContent(anode, deepCopy);
vtkMRMLSegmentationNode* node = vtkMRMLSegmentationNode::SafeDownCast(anode);
if (!node)
{
return;
}
if (deepCopy)
{
if (node->GetSegmentation())
{
if (this->GetSegmentation())
{
this->GetSegmentation()->DeepCopy(node->GetSegmentation());
}
else
{
vtkSmartPointer<vtkSegmentation> newSegmentation
= vtkSmartPointer<vtkSegmentation>::Take(node->GetSegmentation()->NewInstance());
newSegmentation->DeepCopy(node->GetSegmentation());
this->SetAndObserveSegmentation(newSegmentation);
}
}
else
{
// input was nullptr
this->SetAndObserveSegmentation(nullptr);
}
}
else
{
// shallow-copy
this->SetAndObserveSegmentation(node->GetSegmentation());
}
vtkMRMLCopyBeginMacro(anode);
vtkMRMLCopyBooleanMacro(SegmentListFilterEnabled);
vtkMRMLCopyStdStringMacro(SegmentListFilterOptions);
vtkMRMLCopyEndMacro();
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os,indent);
os << indent << "Segmentation:";
if (this->Segmentation)
{
this->Segmentation->PrintSelf(os, indent.GetNextIndent());
}
else
{
os << " (invalid)\n";
}
vtkMRMLPrintBeginMacro(os, indent);
vtkMRMLPrintBooleanMacro(SegmentListFilterEnabled);
vtkMRMLPrintStdStringMacro(SegmentListFilterOptions);
vtkMRMLPrintEndMacro();
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::SetAndObserveSegmentation(vtkSegmentation* segmentation)
{
if (segmentation == this->Segmentation)
{
return;
}
// Remove segment event observations from previous segmentation
if (this->Segmentation)
{
vtkEventBroker::GetInstance()->RemoveObservations(
this->Segmentation, 0, this, this->SegmentationModifiedCallbackCommand);
}
this->SetSegmentation(segmentation);
// Observe segment events in new segmentation
if (this->Segmentation)
{
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::MasterRepresentationModified, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::SegmentAdded, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::SegmentRemoved, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::SegmentModified, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::ContainedRepresentationNamesModified, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::RepresentationModified, this, this->SegmentationModifiedCallbackCommand);
vtkEventBroker::GetInstance()->AddObservation(
this->Segmentation, vtkSegmentation::SegmentsOrderModified, this, this->SegmentationModifiedCallbackCommand);
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::SegmentationModifiedCallback(vtkObject* vtkNotUsed(caller), unsigned long eid, void* clientData, void* callData)
{
vtkMRMLSegmentationNode* self = reinterpret_cast<vtkMRMLSegmentationNode*>(clientData);
if (!self)
{
return;
}
if (!self->Segmentation)
{
// this object is being deleted
return;
}
switch (eid)
{
case vtkSegmentation::MasterRepresentationModified:
self->OnMasterRepresentationModified();
self->InvokeCustomModifiedEvent(eid, callData);
break;
case vtkSegmentation::RepresentationModified:
self->StorableModifiedTime.Modified();
self->InvokeCustomModifiedEvent(eid, callData);
break;
case vtkSegmentation::ContainedRepresentationNamesModified:
self->StorableModifiedTime.Modified();
self->InvokeCustomModifiedEvent(eid);
break;
case vtkSegmentation::SegmentAdded:
self->StorableModifiedTime.Modified();
self->OnSegmentAdded(reinterpret_cast<char*>(callData));
self->InvokeCustomModifiedEvent(eid, callData);
break;
case vtkSegmentation::SegmentRemoved:
self->StorableModifiedTime.Modified();
self->OnSegmentRemoved(reinterpret_cast<char*>(callData));
self->InvokeCustomModifiedEvent(eid, callData);
break;
case vtkSegmentation::SegmentModified:
self->StorableModifiedTime.Modified();
self->OnSegmentModified(reinterpret_cast<char*>(callData));
self->InvokeCustomModifiedEvent(eid, callData);
break;
case vtkSegmentation::SegmentsOrderModified:
self->StorableModifiedTime.Modified();
self->InvokeCustomModifiedEvent(eid);
break;
default:
vtkErrorWithObjectMacro(self, "vtkMRMLSegmentationNode::SegmentationModifiedCallback: Unknown event id "<<eid);
return;
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::OnMasterRepresentationModified()
{
// Reset supported write file types
vtkMRMLSegmentationStorageNode* storageNode = vtkMRMLSegmentationStorageNode::SafeDownCast(this->GetStorageNode());
if (storageNode)
{
storageNode->ResetSupportedWriteFileTypes();
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::OnSegmentAdded(const char* vtkNotUsed(segmentId))
{
vtkMRMLSegmentationDisplayNode* displayNode = vtkMRMLSegmentationDisplayNode::SafeDownCast(this->GetDisplayNode());
if (displayNode)
{
// Make sure the properties of the new segment are as expected even before the first update is triggered (e.g. by slice controller widget).
// removeUnusedDisplayProperties is set to false to prevent removing of display properties of segments
// that are not added to the segmentation node yet (this occurs during scene loading).
displayNode->UpdateSegmentList(false);
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::OnSegmentRemoved(const char* vtkNotUsed(segmentId))
{
vtkMRMLSegmentationDisplayNode* displayNode = vtkMRMLSegmentationDisplayNode::SafeDownCast(this->GetDisplayNode());
if (displayNode)
{
// Make sure the segment is removed from the display properties as well, so that when a new segment is added
// in its place it is properly populated (it will have the same segment ID, so it would simply claim it)
displayNode->UpdateSegmentList();
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::OnSegmentModified(const char* vtkNotUsed(segmentId))
{
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::OnSubjectHierarchyUIDAdded(
vtkMRMLSubjectHierarchyNode* shNode, vtkIdType itemWithNewUID )
{
if (!shNode || !this->Segmentation || !itemWithNewUID)
{
return;
}
// If already has geometry, then do not look for a new one
if (!this->Segmentation->GetConversionParameter(vtkSegmentationConverter::GetReferenceImageGeometryParameterName()).empty())
{
return;
}
// If the new UID is empty string, then do not look for the segmentation's referenced UID in its UID list
std::string itemUidValueStr = shNode->GetItemUID(itemWithNewUID, vtkMRMLSubjectHierarchyConstants::GetDICOMInstanceUIDName());
if (itemUidValueStr.empty())
{
return;
}
// Get volume node from subject hierarchy item with new UID
vtkMRMLScalarVolumeNode* referencedVolumeNode = vtkMRMLScalarVolumeNode::SafeDownCast(
shNode->GetItemDataNode(itemWithNewUID) );
if (!referencedVolumeNode)
{
// If associated node is not a volume, then return
return;
}
// Get associated subject hierarchy item
vtkIdType segmentationShItemID = shNode->GetItemByDataNode(this);
if (!segmentationShItemID)
{
// If segmentation is not in subject hierarchy, then we cannot find its DICOM references
return;
}
// Get DICOM references from segmentation subject hierarchy node
std::string referencedInstanceUIDsAttribute = shNode->GetItemAttribute(
segmentationShItemID, vtkMRMLSubjectHierarchyConstants::GetDICOMReferencedInstanceUIDsAttributeName() );
if (referencedInstanceUIDsAttribute.empty())
{
// No references
return;
}
// If the subject hierarchy node that got a new UID has a DICOM instance UID referenced
// from this segmentation, then use its geometry as image geometry conversion parameter
std::vector<std::string> referencedSopInstanceUids;
vtkMRMLSubjectHierarchyNode::DeserializeUIDList(referencedInstanceUIDsAttribute, referencedSopInstanceUids);
bool referencedVolumeFound = false;
bool warningLogged = false;
std::vector<std::string>::iterator uidIt;
for (uidIt = referencedSopInstanceUids.begin(); uidIt != referencedSopInstanceUids.end(); ++uidIt)
{
// If we find the instance UID, then we set the geometry
if (itemUidValueStr.find(*uidIt) != std::string::npos)
{
// Only set the reference once, but check all UIDs
if (!referencedVolumeFound)
{
// Set reference image geometry parameter if volume node is found
this->SetReferenceImageGeometryParameterFromVolumeNode(referencedVolumeNode);
referencedVolumeFound = true;
}
}
// If referenced UID is not contained in found node, then warn user
else if (referencedVolumeFound && !warningLogged)
{
vtkWarningMacro("vtkMRMLSegmentationNode::OnSubjectHierarchyUIDAdded: Referenced volume for segmentation '"
<< this->Name << "' found (" << referencedVolumeNode->GetName() << "), but some referenced UIDs are not present in it! (maybe only partial volume was loaded?)");
// Only log warning once for this node
warningLogged = true;
}
}
}
//----------------------------------------------------------------------------
vtkMRMLStorageNode* vtkMRMLSegmentationNode::CreateDefaultStorageNode()
{
vtkMRMLScene* scene = this->GetScene();
if (scene == nullptr)
{
vtkErrorMacro("CreateDefaultStorageNode failed: scene is invalid");
return nullptr;
}
return vtkMRMLStorageNode::SafeDownCast(
scene->CreateNodeByClass("vtkMRMLSegmentationStorageNode"));
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::CreateDefaultDisplayNodes()
{
if (vtkMRMLSegmentationDisplayNode::SafeDownCast(this->GetDisplayNode()))
{
// Display node already exists
return;
}
if (this->GetScene() == nullptr)
{
vtkErrorMacro("vtkMRMLSegmentationNode::CreateDefaultDisplayNodes failed: Scene is invalid");
return;
}
vtkMRMLSegmentationDisplayNode* displayNode = vtkMRMLSegmentationDisplayNode::SafeDownCast(
this->GetScene()->AddNewNodeByClass("vtkMRMLSegmentationDisplayNode") );
this->SetAndObserveDisplayNodeID(displayNode->GetID());
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::ApplyTransformMatrix(vtkMatrix4x4* transformMatrix)
{
vtkTransform* transform = vtkTransform::New();
transform->SetMatrix(transformMatrix);
this->ApplyTransform(transform);
transform->Delete();
}
//----------------------------------------------------------------------------
void vtkMRMLSegmentationNode::ApplyTransform(vtkAbstractTransform* transform)
{
if (!this->Segmentation)
{
return;
}
// Apply transform on segmentation
bool wasEnabled = this->Segmentation->SetMasterRepresentationModifiedEnabled(false);
vtkSmartPointer<vtkTransform> linearTransform = vtkSmartPointer<vtkTransform>::New();
if (vtkOrientedImageDataResample::IsTransformLinear(transform, linearTransform))
{
this->Segmentation->ApplyLinearTransform(transform);
}
else
{
this->Segmentation->ApplyNonLinearTransform(transform);
}
this->Segmentation->SetMasterRepresentationModifiedEnabled(wasEnabled);
this->Segmentation->InvalidateNonMasterRepresentations();
// Make sure preferred display representations exist after transformation
// (it is invalidated in the process unless it is the master representation)
char* preferredDisplayRepresentation2D = nullptr;
char* preferredDisplayRepresentation3D = nullptr;
vtkMRMLSegmentationDisplayNode* displayNode = vtkMRMLSegmentationDisplayNode::SafeDownCast(this->GetDisplayNode());
if (displayNode)
{
preferredDisplayRepresentation2D = displayNode->GetPreferredDisplayRepresentationName2D();
preferredDisplayRepresentation3D = displayNode->GetPreferredDisplayRepresentationName3D();
}
// Make sure preferred display representations exist after transformation
// (it was invalidated in the process unless it is the master representation)
if (displayNode)
{
if (preferredDisplayRepresentation2D)
{
this->Segmentation->CreateRepresentation(preferredDisplayRepresentation2D);
}
if (preferredDisplayRepresentation3D)
{
this->Segmentation->CreateRepresentation(preferredDisplayRepresentation3D);
}
// Need to set preferred representations again, as conversion sets them to the last converted one
displayNode->SetPreferredDisplayRepresentationName2D(preferredDisplayRepresentation2D);
displayNode->SetPreferredDisplayRepresentationName3D(preferredDisplayRepresentation3D);
}
}
//----------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::CanApplyNonLinearTransforms() const
{
return true;
}
//---------------------------------------------------------------------------
// Global RAS in the form (Xmin, Xmax, Ymin, Ymax, Zmin, Zmax)
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::GetRASBounds(double bounds[6])
{
if (this->GetParentTransformNode() == nullptr)
{
// Segmentation is not transformed
this->GetBounds(bounds);
}
else
{
// Segmentation is transformed
vtkNew<vtkGeneralTransform> segmentationToRASTransform;
vtkMRMLTransformNode::GetTransformBetweenNodes(this->GetParentTransformNode(), nullptr, segmentationToRASTransform.GetPointer());
double bounds_Segmentation[6] = { 1, -1, 1, -1, 1, -1 };
this->GetBounds(bounds_Segmentation);
vtkOrientedImageDataResample::TransformBounds(bounds_Segmentation, segmentationToRASTransform.GetPointer(), bounds);
}
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::GetBounds(double bounds[6])
{
vtkMath::UninitializeBounds(bounds);
if (this->Segmentation)
{
this->Segmentation->GetBounds(bounds);
}
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::GenerateMergedLabelmap(
vtkOrientedImageData* mergedImageData,
int extentComputationMode,
vtkOrientedImageData* mergedLabelmapGeometry/*=nullptr*/,
const std::vector<std::string>& segmentIDs/*=std::vector<std::string>()*/,
vtkIntArray* labelValues/*=nullptr*/
)
{
return this->Segmentation->GenerateMergedLabelmap(mergedImageData, extentComputationMode, mergedLabelmapGeometry, segmentIDs, labelValues);
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::GenerateMergedLabelmapForAllSegments(vtkOrientedImageData* mergedImageData, int extentComputationMode,
vtkOrientedImageData* mergedLabelmapGeometry /*=nullptr*/, vtkStringArray* segmentIDs /*=nullptr*/, vtkIntArray* labelValues/*nullptr*/)
{
std::vector<std::string> segmentIDsVector;
if (segmentIDs)
{
for (int i = 0; i < segmentIDs->GetNumberOfValues(); i++)
{
segmentIDsVector.push_back(segmentIDs->GetValue(i));
}
}
return this->GenerateMergedLabelmap(mergedImageData, extentComputationMode, mergedLabelmapGeometry, segmentIDsVector, labelValues);
}
//-----------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::GenerateEditMask(vtkOrientedImageData* maskImage, int editMode,
vtkOrientedImageData* referenceGeometry,
std::string editedSegmentID/*=""*/, std::string maskSegmentID/*=""*/,
vtkOrientedImageData* masterVolume/*=nullptr*/, double editableIntensityRange[2]/*=nullptr*/,
vtkMRMLSegmentationDisplayNode* displayNode/*=nullptr*/)
{
if (!maskImage)
{
vtkErrorMacro("vtkMRMLSegmentationNode::GenerateEditMask: Invalid input mask image");
return false;
}
int extent[6] = { 0, -1, 0, -1, 0, -1 };
maskImage->SetExtent(extent);
if (!referenceGeometry)
{
vtkErrorMacro("vtkMRMLSegmentationNode::GenerateEditMask: Invalid reference geometry");
return false;
}
referenceGeometry->GetExtent(extent);
if (extent[0] > extent[1]
|| extent[2] > extent[3]
|| extent[4] > extent[5])
{
// input reference geometry is empty, so we don't need to generate a mask
return true;
}
std::vector<std::string> allSegmentIDs;
this->GetSegmentation()->GetSegmentIDs(allSegmentIDs);
std::vector<std::string> visibleSegmentIDs;
if (editMode == vtkMRMLSegmentationNode::EditAllowedInsideVisibleSegments
|| editMode == vtkMRMLSegmentationNode::EditAllowedOutsideVisibleSegments)
{
if (!displayNode)
{
displayNode = vtkMRMLSegmentationDisplayNode::SafeDownCast(this->GetDisplayNode());
}
if (displayNode)
{
for (std::vector<std::string>::iterator segmentIDIt = allSegmentIDs.begin(); segmentIDIt != allSegmentIDs.end(); ++segmentIDIt)
{
if (displayNode->GetSegmentVisibility(*segmentIDIt))
{
visibleSegmentIDs.push_back(*segmentIDIt);
}
}
}
else
{
vtkErrorMacro("vtkMRMLSegmentationNode::GenerateEditMask: Could not find valid display node");
return false;
}
}
std::vector<std::string> maskSegmentIDs;
bool paintInsideSegments = false;
switch (editMode)
{
case vtkMRMLSegmentationNode::EditAllowedEverywhere:
paintInsideSegments = false;
break;
case vtkMRMLSegmentationNode::EditAllowedInsideAllSegments:
paintInsideSegments = true;
maskSegmentIDs = allSegmentIDs;
break;
case vtkMRMLSegmentationNode::EditAllowedInsideVisibleSegments:
paintInsideSegments = true;
maskSegmentIDs = visibleSegmentIDs;
break;
case vtkMRMLSegmentationNode::EditAllowedOutsideAllSegments:
paintInsideSegments = false;
maskSegmentIDs = allSegmentIDs;
break;
case vtkMRMLSegmentationNode::EditAllowedOutsideVisibleSegments:
paintInsideSegments = false;
maskSegmentIDs = visibleSegmentIDs;
break;
case vtkMRMLSegmentationNode::EditAllowedInsideSingleSegment:
paintInsideSegments = true;
if (!maskSegmentID.empty())
{
maskSegmentIDs.push_back(maskSegmentID);
}
else
{
vtkWarningMacro("vtkMRMLSegmentationNode::GenerateEditMask: PaintAllowedInsideSingleSegment selected but no mask segment is specified");
}
break;
default:
vtkErrorMacro("vtkMRMLSegmentationNode::GenerateEditMask: unknown mask mode");
return false;
}
if (!paintInsideSegments)
{
// Exclude edited segment from "outside" mask
maskSegmentIDs.erase(std::remove(maskSegmentIDs.begin(), maskSegmentIDs.end(), editedSegmentID), maskSegmentIDs.end());
}
maskImage->SetExtent(extent);
vtkNew<vtkMatrix4x4> referenceImageToWorldMatrix;
referenceGeometry->GetImageToWorldMatrix(referenceImageToWorldMatrix.GetPointer());
maskImage->SetImageToWorldMatrix(referenceImageToWorldMatrix.GetPointer());
if (maskSegmentIDs.empty())
{
// If we passed empty segment list to GenerateSharedLabelmap then it would use all segment IDs,
// instead of filling the volume with a single value. Therefore, we need to handle this special case separately here.
maskImage->AllocateScalars(VTK_UNSIGNED_CHAR, 1);
vtkOrientedImageDataResample::FillImage(maskImage, paintInsideSegments ? 1 : 0);
}
else
{
maskImage->AllocateScalars(VTK_SHORT, 1); // Change scalar type from unsigned int back to short for shared labelmap generation
this->GenerateMergedLabelmap(maskImage, vtkSegmentation::EXTENT_UNION_OF_SEGMENTS, referenceGeometry, maskSegmentIDs);
vtkNew<vtkImageThreshold> threshold;
threshold->SetInputData(maskImage);
threshold->SetInValue(paintInsideSegments ? 1 : 0);
threshold->SetOutValue(paintInsideSegments ? 0 : 1);
threshold->ReplaceInOn();
threshold->ThresholdByLower(0);
threshold->SetOutputScalarType(VTK_UNSIGNED_CHAR);
threshold->Update();
maskImage->DeepCopy(threshold->GetOutput());
maskImage->SetImageToWorldMatrix(referenceImageToWorldMatrix.GetPointer());
}
// Apply threshold mask if paint threshold is turned on
if (masterVolume != nullptr && editableIntensityRange != nullptr)
{
// Create threshold image
vtkNew<vtkImageThreshold> threshold;
threshold->SetInputData(masterVolume);
threshold->ThresholdBetween(editableIntensityRange[0], editableIntensityRange[1]);
threshold->SetInValue(1);
threshold->SetOutValue(0);
threshold->SetOutputScalarType(VTK_UNSIGNED_CHAR);
threshold->Update();
vtkNew<vtkOrientedImageData> thresholdMask; // == 0 in editable region
thresholdMask->ShallowCopy(threshold->GetOutput());
vtkNew<vtkMatrix4x4> masterVolumeToWorldMatrix;
masterVolume->GetImageToWorldMatrix(masterVolumeToWorldMatrix.GetPointer());
thresholdMask->SetImageToWorldMatrix(masterVolumeToWorldMatrix.GetPointer());
if (!vtkOrientedImageDataResample::ApplyImageMask(maskImage, thresholdMask.GetPointer(), 1))
{
vtkErrorMacro("vtkMRMLSegmentationNode::GenerateEditMask: failed to apply intensity mask");
return false;
}
}
return true;
}
//---------------------------------------------------------------------------
vtkIdType vtkMRMLSegmentationNode::GetSegmentSubjectHierarchyItem(std::string segmentID, vtkMRMLSubjectHierarchyNode* shNode)
{
if (!shNode)
{
vtkErrorMacro("GetSegmentSubjectHierarchyItem: Invalid subject hierarchy");
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
vtkIdType segmentationvtkIdType = shNode->GetItemByDataNode(this);
if (!segmentationvtkIdType)
{
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
// Find child item of segmentation subject hierarchy item that has the requested segment ID
std::vector<vtkIdType> segmentationChildItemIDs;
shNode->GetItemChildren(segmentationvtkIdType, segmentationChildItemIDs, false);
std::vector<vtkIdType>::iterator childIt;
for (childIt=segmentationChildItemIDs.begin(); childIt!=segmentationChildItemIDs.end(); ++childIt)
{
vtkIdType childItemID = (*childIt);
std::string childSegmentID = shNode->GetItemAttribute(childItemID, vtkMRMLSegmentationNode::GetSegmentIDAttributeName());
if (!childSegmentID.empty() && !childSegmentID.compare(segmentID))
{
return childItemID;
}
}
return vtkMRMLSubjectHierarchyNode::INVALID_ITEM_ID;
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::SetReferenceImageGeometryParameterFromVolumeNode(vtkMRMLScalarVolumeNode* volumeNode)
{
if (!volumeNode || !volumeNode->GetImageData())
{
return;
}
if (!this->Segmentation)
{
vtkSmartPointer<vtkSegmentation> segmentation = vtkSmartPointer<vtkSegmentation>::New();
this->SetAndObserveSegmentation(segmentation);
}
// Get serialized geometry of selected volume
vtkSmartPointer<vtkMatrix4x4> volumeIjkToRasMatrix = vtkSmartPointer<vtkMatrix4x4>::New();
volumeNode->GetIJKToRASMatrix(volumeIjkToRasMatrix);
// If there is a linear transform between the reference volume and segmentation then transform the geometry
// to be aligned with the reference volume.
if (volumeNode->GetParentTransformNode() != this->GetParentTransformNode())
{
vtkSmartPointer<vtkGeneralTransform> volumeToSegmentationTransform = vtkSmartPointer<vtkGeneralTransform>::New();
vtkMRMLTransformNode::GetTransformBetweenNodes(volumeNode->GetParentTransformNode(), this->GetParentTransformNode(), volumeToSegmentationTransform);
if (vtkMRMLTransformNode::IsGeneralTransformLinear(volumeToSegmentationTransform))
{
vtkNew<vtkMatrix4x4> volumeToSegmentationMatrix;
vtkMRMLTransformNode::GetMatrixTransformBetweenNodes(volumeNode->GetParentTransformNode(), this->GetParentTransformNode(), volumeToSegmentationMatrix.GetPointer());
vtkMatrix4x4::Multiply4x4(volumeToSegmentationMatrix.GetPointer(), volumeIjkToRasMatrix, volumeIjkToRasMatrix);
}
}
std::string serializedImageGeometry = vtkSegmentationConverter::SerializeImageGeometry(
volumeIjkToRasMatrix, volumeNode->GetImageData() );
// Set parameter
this->Segmentation->SetConversionParameter(
vtkSegmentationConverter::GetReferenceImageGeometryParameterName(), serializedImageGeometry);
// Set node reference from segmentation to reference geometry volume
this->SetNodeReferenceID(
vtkMRMLSegmentationNode::GetReferenceImageGeometryReferenceRole().c_str(), volumeNode->GetID() );
}
//---------------------------------------------------------------------------
std::string vtkMRMLSegmentationNode::AddSegmentFromClosedSurfaceRepresentation(vtkPolyData* polyData,
std::string segmentName/* ="" */, double color[3] /* =nullptr */,
std::string vtkNotUsed(segmentId)/* ="" */)
{
if (!this->Segmentation)
{
vtkErrorMacro("AddSegmentFromClosedSurfaceRepresentation: Invalid segmentation");
return "";
}
vtkNew<vtkSegment> newSegment;
if (!segmentName.empty())
{
newSegment->SetName(segmentName.c_str());
}
if (color!=nullptr)
{
newSegment->SetColor(color);
}
newSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationClosedSurfaceRepresentationName(), polyData);
if (!this->Segmentation->AddSegment(newSegment.GetPointer()))
{
return "";
}
return this->Segmentation->GetSegmentIdBySegment(newSegment.GetPointer());
}
//---------------------------------------------------------------------------
std::string vtkMRMLSegmentationNode::AddSegmentFromBinaryLabelmapRepresentation(vtkOrientedImageData* imageData,
std::string segmentName/* ="" */, double color[3] /* =nullptr */,
std::string vtkNotUsed(segmentId)/* ="" */)
{
if (!this->Segmentation)
{
vtkErrorMacro("AddSegmentFromBinaryLabelmapRepresentation: Invalid segmentation");
return "";
}
vtkNew<vtkSegment> newSegment;
if (!segmentName.empty())
{
newSegment->SetName(segmentName.c_str());
}
if (color != nullptr)
{
newSegment->SetColor(color);
}
newSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName(), imageData);
if (!this->Segmentation->AddSegment(newSegment.GetPointer()))
{
return "";
}
return this->Segmentation->GetSegmentIdBySegment(newSegment.GetPointer());
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::RemoveSegment(const std::string& segmentID)
{
if (!this->Segmentation)
{
vtkErrorMacro("RemoveSegment: Invalid segmentation");
return;
}
this->Segmentation->RemoveSegment(segmentID);
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::CreateBinaryLabelmapRepresentation()
{
if (!this->Segmentation)
{
vtkErrorMacro("CreateBinaryLabelmapRepresentation: Invalid segmentation");
return false;
}
return this->Segmentation->CreateRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName());
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::RemoveBinaryLabelmapRepresentation()
{
if (!this->Segmentation)
{
vtkErrorMacro("RemoveBinaryLabelmapRepresentation: Invalid segmentation");
return;
}
this->Segmentation->RemoveRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName());
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::GetBinaryLabelmapRepresentation(const std::string segmentId, vtkOrientedImageData* outputBinaryLabelmap)
{
if (!this->Segmentation)
{
vtkErrorMacro("GetBinaryLabelmapRepresentation: Invalid segmentation");
return false;
}
vtkSegment* segment = this->Segmentation->GetSegment(segmentId);
if (!segment)
{
vtkErrorMacro("GetBinaryLabelmapRepresentation: Invalid segment");
return false;
}
vtkOrientedImageData* binaryLabelmap = vtkOrientedImageData::SafeDownCast(
segment->GetRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()));
if (!binaryLabelmap)
{
vtkErrorMacro("GetBinaryLabelmapRepresentation: No binary labelmap representation in segment");
return false;
}
vtkNew<vtkImageThreshold> threshold;
threshold->SetInputData(binaryLabelmap);
threshold->ThresholdBetween(segment->GetLabelValue(), segment->GetLabelValue());
threshold->SetInValue(1);
threshold->SetOutValue(0);
threshold->Update();
outputBinaryLabelmap->ShallowCopy(threshold->GetOutput());
outputBinaryLabelmap->CopyDirections(binaryLabelmap);
return true;
}
//---------------------------------------------------------------------------
vtkOrientedImageData* vtkMRMLSegmentationNode::GetBinaryLabelmapInternalRepresentation(const std::string segmentId)
{
if (!this->Segmentation)
{
vtkErrorMacro("GetBinaryLabelmapRepresentation: Invalid segmentation");
return nullptr;
}
vtkSegment* segment = this->Segmentation->GetSegment(segmentId);
if (!segment)
{
vtkErrorMacro("GetBinaryLabelmapRepresentation: Invalid segment");
return nullptr;
}
return vtkOrientedImageData::SafeDownCast(segment->GetRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()));
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::CreateClosedSurfaceRepresentation()
{
if (!this->Segmentation)
{
vtkErrorMacro("CreateClosedSurfaceRepresentation: Invalid segmentation");
return false;
}
return this->Segmentation->CreateRepresentation(vtkSegmentationConverter::GetSegmentationClosedSurfaceRepresentationName());
}
//---------------------------------------------------------------------------
void vtkMRMLSegmentationNode::RemoveClosedSurfaceRepresentation()
{
if (!this->Segmentation)
{
vtkErrorMacro("RemoveClosedSurfaceRepresentation: Invalid segmentation");
return;
}
this->Segmentation->RemoveRepresentation(vtkSegmentationConverter::GetSegmentationClosedSurfaceRepresentationName());
}
//---------------------------------------------------------------------------
bool vtkMRMLSegmentationNode::GetClosedSurfaceRepresentation(const std::string segmentId, vtkPolyData* outputClosedSurface)
{
if (!this->Segmentation)
{
vtkErrorMacro("GetClosedSurfaceRepresentation: Invalid segmentation");
return false;
}
vtkSegment* segment = this->Segmentation->GetSegment(segmentId);
if (!segment)
{
vtkErrorMacro("GetClosedSurfaceRepresentation: Invalid segment");
return false;
}
vtkDataObject* closedSurface = segment->GetRepresentation(vtkSegmentationConverter::GetSegmentationClosedSurfaceRepresentationName());
if (!closedSurface)
{
vtkErrorMacro("GetClosedSurfaceRepresentation: No closed surface representation in segment");
return false;
}
outputClosedSurface->DeepCopy(closedSurface);
return true;
}
//---------------------------------------------------------------------------
vtkPolyData* vtkMRMLSegmentationNode::GetClosedSurfaceInternalRepresentation(const std::string segmentId)
{
if (!this->Segmentation)
{
vtkErrorMacro("GetClosedSurfaceRepresentation: Invalid segmentation");
return nullptr;
}
vtkSegment* segment = this->Segmentation->GetSegment(segmentId);
if (!segment)
{
vtkErrorMacro("GetClosedSurfaceRepresentation: Invalid segment");
return nullptr;
}
return vtkPolyData::SafeDownCast(segment->GetRepresentation(vtkSegmentationConverter::GetSegmentationClosedSurfaceRepresentationName()));
}