forked from OHIF/Viewers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegmentationService.ts
More file actions
2271 lines (1971 loc) · 76.1 KB
/
Copy pathSegmentationService.ts
File metadata and controls
2271 lines (1971 loc) · 76.1 KB
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 {
cache,
Enums as csEnums,
eventTarget,
geometryLoader,
getEnabledElementByViewportId,
imageLoader,
Types as csTypes,
utilities as csUtils,
metaData,
} from '@cornerstonejs/core';
import { ViewportType } from '@cornerstonejs/core/enums';
import { isVolume3DViewportType } from '../../utils/getLegacyViewportType';
import {
Enums as csToolsEnums,
segmentation as cstSegmentation,
Types as cstTypes,
annotation as cstAnnotation,
} from '@cornerstonejs/tools';
import { PubSubService, Types as OHIFTypes } from '@ohif/core';
import i18n from '@ohif/i18n';
import { VOLUME_LOADER_SCHEME } from '../../constants';
import { mapROIContoursToRTStructData } from './RTSTRUCT/mapROIContoursToRTStructData';
import { SegmentationPresentation, SegmentationPresentationItem } from '../../types/Presentation';
import { EasingFunctionEnum, EasingFunctionMap } from '../../utils/transitions';
import { ViewReference } from '@cornerstonejs/core/types';
import {
LegacySegmentationBackend,
NextSegmentationBackend,
type ISegmentationBackend,
type ISegmentationServiceInternals,
} from './backends';
// Sanctioned flag read: the SEG data shape (single- vs multi-layer) is fixed at
// load time, before any target viewport exists, so this one seg-backend dispatch
// cannot use a per-viewport capability check and reads the session flag instead.
import { isNextViewportsEnabled } from '../../utils/nextViewports';
import { isNextViewport } from '../ViewportService/adapter';
const { DefaultHistoryMemo } = csUtils.HistoryMemo;
const {
Labelmap: LABELMAP,
Contour: CONTOUR,
Surface: SURFACE,
} = csToolsEnums.SegmentationRepresentations;
const {
getLabelmapImageIds,
helpers: { convertStackToVolumeLabelmap },
state: { addColorLUT },
triggerSegmentationEvents: { triggerSegmentationRepresentationModified },
} = cstSegmentation;
export type SegmentRepresentation = {
segmentIndex: number;
color: csTypes.Color;
opacity: number;
visible: boolean;
};
export type SegmentationData = cstTypes.Segmentation;
export type SegmentationRepresentation = cstTypes.SegmentationRepresentation & {
viewportId: string;
id: string;
label: string;
fallbackLabel?: string;
styles: cstTypes.RepresentationStyle;
segments: {
[key: number]: SegmentRepresentation;
};
};
export type SegmentationInfo = {
segmentation: SegmentationData;
representation?: SegmentationRepresentation;
};
const EVENTS = {
SEGMENTATION_MODIFIED: 'event::segmentation_modified',
// fired when the segmentation is added
SEGMENTATION_ADDED: 'event::segmentation_added',
//
SEGMENTATION_DATA_MODIFIED: 'event::segmentation_data_modified',
// fired when the segmentation is removed
SEGMENTATION_REMOVED: 'event::segmentation_removed',
//
// fired when segmentation representation is added
SEGMENTATION_REPRESENTATION_MODIFIED: 'event::segmentation_representation_modified',
// fired when segmentation representation is removed
SEGMENTATION_REPRESENTATION_REMOVED: 'event::segmentation_representation_removed',
//
// LOADING EVENTS
// fired when the active segment is loaded in SEG or RTSTRUCT
SEGMENT_LOADING_COMPLETE: 'event::segment_loading_complete',
// loading completed for all segments
SEGMENTATION_LOADING_COMPLETE: 'event::segmentation_loading_complete',
// fired when a contour annotation cut merge process is completed
SEGMENTATION_ANNOTATION_CUT_MERGE_PROCESS_COMPLETED:
'event::annotation_cut_merge_process_completed',
SEGMENTATION_STYLE_MODIFIED: 'event::segmentation_style_modified',
};
const VALUE_TYPES = {};
class SegmentationService extends PubSubService implements ISegmentationServiceInternals {
static REGISTRATION = {
name: 'segmentationService',
altName: 'SegmentationService',
create: ({ servicesManager }: OHIFTypes.Extensions.ExtensionParams): SegmentationService => {
return new SegmentationService({ servicesManager });
},
};
private _segmentationIdToColorLUTIndexMap: Map<string, number>;
private _segmentationGroupStatsMap: Map<string, any>;
private readonly _legacySegBackend: ISegmentationBackend;
private readonly _nextSegBackend: ISegmentationBackend;
readonly servicesManager: AppTypes.ServicesManager;
highlightIntervalId = null;
readonly EVENTS = EVENTS;
constructor({ servicesManager }) {
super(EVENTS);
this._segmentationIdToColorLUTIndexMap = new Map();
this.servicesManager = servicesManager;
this._segmentationGroupStatsMap = new Map();
// Segmentation backend twins (mirror the viewport backend family). Routed PER
// VIEWPORT via _segBackend() using the adapter's isNextViewport predicate,
// because a flag-on session can mix native and legacy viewports. Both are
// constructed eagerly:
// per-viewport dispatch has no per-session flag to defer on, and the twins read
// state at call time (post-init), not at construction.
this._legacySegBackend = new LegacySegmentationBackend(this);
this._nextSegBackend = new NextSegmentationBackend();
}
/**
* Picks the segmentation backend lane for a specific viewport: the native
* ("next") twin for a raw GenericViewport (PlanarViewport), the legacy twin
* otherwise. Mirrors viewportOperations' per-viewport dispatch.
*/
private _segBackend(viewport: csTypes.IViewport): ISegmentationBackend {
return isNextViewport(viewport) ? this._nextSegBackend : this._legacySegBackend;
}
public onModeEnter(): void {
this._initSegmentationService();
}
public onModeExit(): void {
this.destroy();
}
/**
* Retrieves a segmentation by its ID.
*
* @param segmentationId - The unique identifier of the segmentation to retrieve.
* @returns The segmentation object if found, or undefined if not found.
*
* @remarks
* This method directly accesses the cornerstone tools segmentation state to fetch
* the segmentation data. It's useful when you need to access specific properties
* or perform operations on a particular segmentation.
*/
public getSegmentation(segmentationId: string): cstTypes.Segmentation | undefined {
return cstSegmentation.state.getSegmentation(segmentationId);
}
/**
* Retrieves all segmentations from the cornerstone tools segmentation state.
*
* @returns An array of all segmentations currently stored in the state
*
* @remarks
* This is a convenience method that directly accesses the cornerstone tools
* segmentation state to get all available segmentations. It returns the raw
* segmentation objects without any additional processing or filtering.
*/
public getSegmentations(): cstTypes.Segmentation[] | [] {
return cstSegmentation.state.getSegmentations();
}
public getPresentation(viewportId: string): SegmentationPresentation {
const segmentationPresentations: SegmentationPresentation = [];
const segmentationsMap = new Map<string, SegmentationPresentationItem>();
const representations = this.getSegmentationRepresentations(viewportId);
for (const representation of representations) {
if (!representation) {
continue;
}
const { segmentationId, type } = representation;
segmentationsMap.set(segmentationId, {
segmentationId,
type,
hydrated: true,
config: representation.config || {},
});
}
// Check inside the removedDisplaySetAndRepresentationMaps to see if any of the representations are not hydrated
// const hydrationMap = this._segmentationRepresentationHydrationMaps.get(presentationId);
// if (hydrationMap) {
// hydrationMap.forEach(rep => {
// segmentationsMap.set(rep.segmentationId, {
// segmentationId: rep.segmentationId,
// type: rep.type,
// hydrated: rep.hydrated,
// config: rep.config || {},
// });
// });
// }
// // Convert the Map to an array
segmentationPresentations.push(...segmentationsMap.values());
return segmentationPresentations;
}
public getRepresentationsForSegmentation(
segmentationId: string
): { viewportId: string; representations: any[] }[] {
const representations =
cstSegmentation.state.getSegmentationRepresentationsBySegmentationId(segmentationId);
return representations;
}
/**
* Retrieves segmentation representations (labelmap, contour, surface) based on specified criteria.
*
* @param viewportId - The ID of the viewport.
* @param specifier - An object containing optional `segmentationId` and `type` to filter the representations.
* @returns An array of `SegmentationRepresentation` matching the criteria, or an empty array if none are found.
*
* @remarks
* This method filters the segmentation representations according to the provided `specifier`:
* - **No `segmentationId` or `type` provided**: Returns all representations associated with the given `viewportId`.
* - **Only `segmentationId` provided**: Returns all representations with that `segmentationId`, regardless of `viewportId`.
* - **Only `type` provided**: Returns all representations of that `type` associated with the given `viewportId`.
* - **Both `segmentationId` and `type` provided**: Returns representations matching both criteria, regardless of `viewportId`.
*/
public getSegmentationRepresentations(
viewportId: string,
specifier: {
segmentationId?: string;
type?: csToolsEnums.SegmentationRepresentations;
} = {}
): SegmentationRepresentation[] {
// Get all representations for the viewportId
const representations = cstSegmentation.state.getSegmentationRepresentations(
viewportId,
specifier
);
// Map to our SegmentationRepresentation type
const ohifRepresentations = representations.map(repr =>
this._toOHIFSegmentationRepresentation(viewportId, repr)
);
return ohifRepresentations;
}
public destroy = () => {
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_MODIFIED,
this._onSegmentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REMOVED,
this._onSegmentationRemovedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_DATA_MODIFIED,
this._onSegmentationDataModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_MODIFIED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_ADDED,
this._onSegmentationRepresentationModifiedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_REPRESENTATION_REMOVED,
this._onSegmentationRepresentationRemovedFromSource
);
eventTarget.removeEventListener(
csToolsEnums.Events.SEGMENTATION_ADDED,
this._onSegmentationAddedFromSource
);
this.reset();
};
public async addSegmentationRepresentation(
viewportId: string,
{
segmentationId,
predecessorImageId,
type,
config,
suppressEvents = false,
}: {
segmentationId: string;
predecessorImageId?: string;
type?: csToolsEnums.SegmentationRepresentations;
config?: {
blendMode?: csEnums.BlendModes;
useSliceRendering?: boolean;
};
suppressEvents?: boolean;
}
): Promise<void> {
const segmentation = this.getSegmentation(segmentationId);
if (!segmentation) {
console.warn(
`addSegmentationRepresentation: segmentation "${segmentationId}" is not in state yet`
);
return;
}
if (!segmentation.predecessorImageId && predecessorImageId) {
segmentation.predecessorImageId = predecessorImageId;
}
const csViewport = this.getAndValidateViewport(viewportId);
if (!csViewport) {
return;
}
// A stale/invalid segmentationId yields no segmentation; fail fast with a clear
// message instead of dereferencing representationData deep inside the backend
// classification below.
if (!segmentation) {
throw new Error(
`SegmentationService: cannot add representation - segmentation "${segmentationId}" not found.`
);
}
const colorLUTIndex = this._segmentationIdToColorLUTIndexMap.get(segmentationId);
let isConverted = false;
const defaultRepresentationType: csToolsEnums.SegmentationRepresentations =
isVolume3DViewportType(csViewport) ? SURFACE : LABELMAP;
let representationTypeToUse = type || defaultRepresentationType;
if (representationTypeToUse === LABELMAP) {
({ representationTypeToUse, isConverted } = await this._segBackend(
csViewport
).classifyAndPrepareLabelmapAdd(
csViewport,
segmentation,
viewportId,
segmentationId,
representationTypeToUse
));
// Overlap precondition: an overlapping SEG is registered as multiple labelmap
// layers, but cornerstone only stacks them (slice rendering) when the viewport
// renders as a volume slice (VTK_VOLUME_SLICE) — i.e. an MPR/volume viewport. On
// a stack/acquisition viewport the render plan falls back to a single layer, so
// only the primary group is visible. Warn rather than fail silently.
const labelmapLayers = segmentation?.representationData?.[LABELMAP]?.labelmaps;
const isOverlapping = labelmapLayers && Object.keys(labelmapLayers).length > 1;
if (
isOverlapping &&
isNextViewport(csViewport) &&
!csUtils.viewportIsInVolumeMode(csViewport)
) {
console.warn(
`Overlapping segmentation ${segmentationId} has multiple labelmap layers, but ` +
`viewport ${viewportId} does not render as a volume slice (VTK_VOLUME_SLICE); ` +
`only the primary layer will be visible. Display the segmentation in an ` +
`MPR/volume layout to see all overlapping segments.`
);
}
}
await this._addSegmentationRepresentation(
viewportId,
segmentationId,
representationTypeToUse,
colorLUTIndex,
isConverted,
config
);
if (!suppressEvents) {
this._broadcastEvent(this.EVENTS.SEGMENTATION_REPRESENTATION_MODIFIED, { segmentationId });
}
}
/**
* Creates an labelmap segmentation for a given display set
*
* @param displaySet - The display set to create the segmentation for.
* @param options - Optional parameters for creating the segmentation.
* @param options.segmentationId - Custom segmentation ID. If not provided, a UUID will be generated.
* @param options.FrameOfReferenceUID - Frame of reference UID for the segmentation.
* @param options.label - Label for the segmentation.
* @returns A promise that resolves to the created segmentation ID.
*/
public async createLabelmapForDisplaySet(
displaySet: AppTypes.DisplaySet,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
}
): Promise<string> {
return this._createSegmentationForDisplaySet(displaySet, LABELMAP, options);
}
public async createContourForDisplaySet(
displaySet: AppTypes.DisplaySet,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
}
): Promise<string> {
return this._createSegmentationForDisplaySet(displaySet, CONTOUR, options);
}
/**
* Private method to create segmentation for a display set with the specified type
*
* @param displaySet - The display set to create the segmentation for
* @param segmentationType - The type of segmentation (SegmentationRepresentations enum)
* @param options - Optional parameters for creating the segmentation
* @returns A promise that resolves to the created segmentation ID
*/
private async _createSegmentationForDisplaySet(
displaySet: AppTypes.DisplaySet,
segmentationType: SegmentationRepresentations,
options?: {
segmentationId?: string;
segments?: { [segmentIndex: number]: Partial<cstTypes.Segment> };
FrameOfReferenceUID?: string;
label?: string;
}
): Promise<string> {
// Todo: random does not makes sense, make this better, like
// labelmap 1, 2, 3 etc
const segmentationId = options?.segmentationId ?? `${csUtils.uuidv4()}`;
const isDynamicVolume = displaySet.isDynamicVolume;
let referenceImageIds = displaySet.imageIds;
if (isDynamicVolume) {
// get the middle timepoint for referenceImageIds
const timePoints = displaySet.dynamicVolumeInfo.timePoints;
const middleTimePoint = timePoints[Math.floor(timePoints.length / 2)];
referenceImageIds = middleTimePoint;
}
const derivedImages = await imageLoader.createAndCacheDerivedLabelmapImages(referenceImageIds);
const segs = this.getSegmentations();
const label = options?.label || `Segmentation ${segs.length + 1}`;
const segImageIds = derivedImages.map(image => image.imageId);
const segmentationPublicInput: cstTypes.SegmentationPublicInput = {
segmentationId,
representation: {
type: segmentationType,
data: {
imageIds: segImageIds,
// referencedVolumeId: this._getVolumeIdForDisplaySet(displaySet),
referencedImageIds: referenceImageIds,
},
},
config: {
label,
fallbackLabel: `S:${displaySet.SeriesNumber} ${displaySet.Modality}`,
segments:
options?.segments && Object.keys(options.segments).length > 0
? options.segments
: {
1: {
label: `${i18n.t('Segment')} 1`,
active: true,
},
},
cachedStats: {
info: `S${displaySet.SeriesNumber}: ${displaySet.SeriesDescription}`,
},
},
};
// Create a dedicated color LUT up front and remember its index so that every
// representation of this segmentation (one per viewport) reuses the same LUT.
// Otherwise each viewport would get its own default LUT copy and editing a
// segment color on one viewport would not be reflected on the others (the
// segment color appears to revert to the default when interacting elsewhere).
// The caller may pass the id of an existing segmentation, which this method
// updates rather than replaces; keep its LUT so representations already
// rendering it don't diverge from the ones created afterwards.
if (!this._segmentationIdToColorLUTIndexMap.has(segmentationId)) {
const colorLUTIndex = addColorLUT([[0, 0, 0, 0]] as csTypes.ColorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
}
this.addOrUpdateSegmentation(segmentationPublicInput);
return segmentationId;
}
public async createSegmentationForSEGDisplaySet(
segDisplaySet,
options: {
segmentationId?: string;
type: csToolsEnums.SegmentationRepresentations;
} = {
type: LABELMAP,
}
): Promise<string> {
const { type } = options;
let { segmentationId } = options;
const { labelMapImages } = segDisplaySet;
if (type !== LABELMAP) {
throw new Error('Only labelmap type is supported for SEG display sets right now');
}
if (!labelMapImages || !labelMapImages.length) {
throw new Error('SEG reading failed');
}
segmentationId = segmentationId ?? segDisplaySet.displaySetInstanceUID;
const referencedDisplaySetInstanceUID = segDisplaySet.referencedDisplaySetInstanceUID;
const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
referencedDisplaySetInstanceUID
);
const images = referencedDisplaySet.instances;
if (!images.length) {
throw new Error('No instances were provided for the referenced display set of the SEG');
}
// Use the same imageIds as SEG parse (_loadSegments stores these on segDisplaySet).
const imageIds =
segDisplaySet.referencedImageIds ||
(referencedDisplaySet.imageIds as string[] | undefined) ||
images.map(image => image.imageId);
if (!imageIds?.length) {
throw new Error('referencedDisplaySet has no imageIds for SEG');
}
const derivedImages = labelMapImages?.flat();
const derivedImageIds = derivedImages.map(image => image.imageId);
// Note: instance runtime props (frameNumber, imageId, url, ...) are
// intentionally non-enumerable, so this spread deliberately does NOT copy
// them — frameNumber must not be carried onto these derived image entries.
// Read such props off the original instance, never off a copy.
segDisplaySet.images = derivedImages.map(image => ({
...image,
...metaData.get('instance', image.referencedImageId),
}));
segDisplaySet.imageIds = derivedImageIds;
// We should parse the segmentation as separate slices to support overlapping segments.
// This parsing should occur in the CornerstoneJS library adapters.
// For now, we use the volume returned from the library and chop it here.
let firstSegmentedSliceImageId = null;
for (let i = 0; i < derivedImages.length; i++) {
const voxelManager = derivedImages[i].voxelManager as csTypes.IVoxelManager<number>;
const scalarData = voxelManager.getScalarData();
voxelManager.setScalarData(scalarData);
// Check if this slice has any non-zero voxels and we haven't found one yet
if (!firstSegmentedSliceImageId && scalarData.some(value => value !== 0)) {
firstSegmentedSliceImageId = derivedImages[i].referencedImageId;
}
}
// assign the first non zero voxel image id to the segDisplaySet
segDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
const segmentsInfo = segDisplaySet.segMetadata.data;
const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
const colorLUT = [];
segmentsInfo.forEach((segmentInfo, index) => {
if (index === 0) {
colorLUT.push([0, 0, 0, 0]);
return;
}
const {
SegmentedPropertyCategoryCodeSequence,
SegmentNumber,
SegmentLabel,
SegmentAlgorithmType,
SegmentAlgorithmName,
SegmentedPropertyTypeCodeSequence,
rgba,
} = segmentInfo;
colorLUT.push(rgba);
const segmentIndex = Number(SegmentNumber);
const centroid = segDisplaySet.centroids?.get(index);
const imageCentroidXYZ = centroid?.image || { x: 0, y: 0, z: 0 };
const worldCentroidXYZ = centroid?.world || { x: 0, y: 0, z: 0 };
segments[segmentIndex] = {
segmentIndex,
label: SegmentLabel || `Segment ${SegmentNumber}`,
locked: false,
active: false,
cachedStats: {
center: {
image: [imageCentroidXYZ.x, imageCentroidXYZ.y, imageCentroidXYZ.z],
world: [worldCentroidXYZ.x, worldCentroidXYZ.y, worldCentroidXYZ.z],
},
modifiedTime: segDisplaySet.SeriesDate,
category: SegmentedPropertyCategoryCodeSequence
? SegmentedPropertyCategoryCodeSequence.CodeMeaning
: '',
type: SegmentedPropertyTypeCodeSequence
? SegmentedPropertyTypeCodeSequence.CodeMeaning
: '',
algorithmType: SegmentAlgorithmType,
algorithmName: SegmentAlgorithmName,
},
};
});
const colorLUTIndex = addColorLUT(colorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
// Build the segmentation input via the backend twin. At SEG-load there is no
// target viewport yet, so the lane is chosen by the session flag (the one
// viewport-less seg-backend dispatch): the next twin registers overlapping SEGs
// as multiple labelmap layers (slice rendering); the legacy twin keeps the single
// flattened layer (byte-identical).
const segBackend = isNextViewportsEnabled() ? this._nextSegBackend : this._legacySegBackend;
const seg = segBackend.assembleSegmentationDataForSEG({
segmentationId,
segDisplaySet,
derivedImageIds,
referencedImageIds: imageIds as string[],
label: segDisplaySet.SeriesDescription,
fallbackLabel: `S:${segDisplaySet.SeriesNumber} ${segDisplaySet.Modality}`,
segments,
});
segDisplaySet.isLoaded = true;
// Add the segmentation to cornerstone state BEFORE broadcasting that loading is
// complete. Subscribers (e.g. CornerstoneViewportService) react synchronously and
// call addSegmentationRepresentation, which now early-returns when the segmentation
// is not yet in cornerstone state. Broadcasting first would make that guard always
// fire on initial load, silently preventing the representation from being attached.
this.addOrUpdateSegmentation(seg);
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
segDisplaySet,
});
return segmentationId;
}
public async createSegmentationForRTDisplaySet(
rtDisplaySet,
options: {
segmentationId?: string;
type: csToolsEnums.SegmentationRepresentations;
} = {
type: CONTOUR,
}
): Promise<string> {
const { type } = options;
let { segmentationId } = options;
// Currently, only contour representation is supported for RT display
if (type !== CONTOUR) {
throw new Error('Only contour type is supported for RT display sets right now');
}
// Assign segmentationId if not provided
segmentationId = segmentationId ?? rtDisplaySet.displaySetInstanceUID;
const { structureSet } = rtDisplaySet;
if (!structureSet) {
throw new Error(
'To create the contours from RT displaySet, the displaySet should be loaded first. You can perform rtDisplaySet.load() before calling this method.'
);
}
const rtDisplaySetUID = rtDisplaySet.displaySetInstanceUID;
const referencedDisplaySet = this.servicesManager.services.displaySetService.getDisplaySetByUID(
rtDisplaySet.referencedDisplaySetInstanceUID
);
const referencedImageIdsWithGeometry = Array.from(structureSet.ReferencedSOPInstanceUIDsSet);
const referencedImageIds = referencedDisplaySet.imageIds;
// find the first image id that contains a referenced SOP instance UID
const firstSegmentedSliceImageId =
referencedImageIds?.find(imageId =>
referencedImageIdsWithGeometry.some(referencedId =>
imageId.includes(referencedId as string)
)
) || null;
rtDisplaySet.firstSegmentedSliceImageId = firstSegmentedSliceImageId;
if (!structureSet.ROIContours?.length) {
throw new Error(
'The structureSet does not contain any ROIContours. Please ensure the structureSet is loaded first.'
);
}
// Map ROI contours to RT Struct Data
const allRTStructData = mapROIContoursToRTStructData(structureSet, rtDisplaySetUID);
// Sort by segmentIndex for consistency
allRTStructData.sort((a, b) => a.segmentIndex - b.segmentIndex);
const geometryIds = allRTStructData.map(({ geometryId }) => geometryId);
// Initialize SegmentationPublicInput similar to SEG function
const segmentation: cstTypes.SegmentationPublicInput = {
segmentationId,
representation: {
type: CONTOUR,
data: {
geometryIds,
},
},
config: {
label: rtDisplaySet.SeriesDescription,
fallbackLabel: `S:${rtDisplaySet.SeriesNumber} ${rtDisplaySet.Modality}`,
},
};
const segments: { [segmentIndex: string]: cstTypes.Segment } = {};
let segmentsCachedStats = {};
// Create colorLUT array for RT structures
const colorLUT = [[0, 0, 0, 0]]; // First entry is transparent for index 0
// Process each segment similarly to the SEG function
for (let i = 0; i < allRTStructData.length; i++) {
const rtStructData = allRTStructData[i];
const { data, id, color, segmentIndex, geometryId, group } = rtStructData;
// Add the color to the colorLUT array
colorLUT.push(color);
try {
const geometry = await geometryLoader.createAndCacheGeometry(geometryId, {
geometryData: {
data,
id,
color,
frameOfReferenceUID: structureSet.frameOfReferenceUID,
segmentIndex,
},
type: csEnums.GeometryType.CONTOUR,
});
const contourSet = geometry.data as csTypes.IContourSet;
const centroid = contourSet.centroid;
segmentsCachedStats = {
center: { world: centroid },
modifiedTime: rtDisplaySet.SeriesDate, // Using SeriesDate as modifiedTime
};
segments[segmentIndex] = {
label: id,
segmentIndex,
cachedStats: segmentsCachedStats,
locked: false,
active: false,
group,
};
// Broadcast segment loading progress
const numInitialized = Object.keys(segmentsCachedStats).length;
const percentComplete = Math.round((numInitialized / allRTStructData.length) * 100);
this._broadcastEvent(EVENTS.SEGMENT_LOADING_COMPLETE, {
percentComplete,
numSegments: allRTStructData.length,
});
} catch (e) {
console.warn(`Error initializing contour for segment ${segmentIndex}:`, e);
continue; // Continue processing other segments even if one fails
}
}
// Create and register the colorLUT
const colorLUTIndex = addColorLUT(colorLUT);
this._segmentationIdToColorLUTIndexMap.set(segmentationId, colorLUTIndex);
// Assign processed segments to segmentation config
segmentation.config.segments = segments;
// Broadcast segmentation loading complete event
this._broadcastEvent(EVENTS.SEGMENTATION_LOADING_COMPLETE, {
segmentationId,
rtDisplaySet,
});
// Mark the RT display set as loaded
rtDisplaySet.isLoaded = true;
// Add or update the segmentation in the state
this.addOrUpdateSegmentation(segmentation);
return segmentationId;
}
/**
* Adds or updates a segmentation in the state
* @param segmentationId - The ID of the segmentation to add or update
* @param data - The data to add or update the segmentation with
*
* @remarks
* This method handles the addition or update of a segmentation in the state.
* If the segmentation already exists, it updates the existing segmentation.
* If the segmentation does not exist, it adds a new segmentation.
*/
public addOrUpdateSegmentation(
data: cstTypes.SegmentationPublicInput | Partial<cstTypes.Segmentation>
) {
const segmentationId = data.segmentationId;
const existingSegmentation = cstSegmentation.state.getSegmentation(segmentationId);
if (existingSegmentation) {
// Update the existing segmentation
this.updateSegmentationInSource(segmentationId, data as Partial<cstTypes.Segmentation>);
} else if (
'representation' in data &&
(data as cstTypes.SegmentationPublicInput).representation
) {
// Add a new segmentation
this.addSegmentationToSource(data as cstTypes.SegmentationPublicInput);
} else {
console.warn(
`addOrUpdateSegmentation: skipping add for ${segmentationId} — missing representation`
);
}
}
public setActiveSegmentation(viewportId: string, segmentationId: string): void {
cstSegmentation.activeSegmentation.setActiveSegmentation(viewportId, segmentationId);
}
/**
* Gets the active segmentation for a viewport
* @param viewportId - The ID of the viewport to get the active segmentation for
* @returns The active segmentation object, or null if no segmentation is active
*
* @remarks
* This method retrieves the currently active segmentation for the specified viewport.
* The active segmentation is the one that is currently selected for editing operations.
* Returns null if no segmentation is active in the viewport.
*/
public getActiveSegmentation(viewportId: string): cstTypes.Segmentation | null {
return cstSegmentation.activeSegmentation.getActiveSegmentation(viewportId);
}
/**
* Gets the active segment from the active segmentation in a viewport
* @param viewportId - The ID of the viewport to get the active segment from
* @returns The active segment object, or undefined if no segment is active
*
* @remarks
* This method retrieves the currently active segment from the active segmentation
* in the specified viewport. The active segment is the one that is currently
* selected for editing operations. Returns undefined if no segment is active or
* if there is no active segmentation.
*/
public getActiveSegment(viewportId: string): cstTypes.Segment | undefined {
const activeSegmentation = this.getActiveSegmentation(viewportId);
if (!activeSegmentation) {
return;
}
const { segments } = activeSegmentation;
let activeSegment;
for (const segment of Object.values(segments)) {
if (segment.active) {
activeSegment = segment;
break;
}
}
return activeSegment;
}
public hasCustomStyles(specifier: {
viewportId: string;
segmentationId: string;
type: csToolsEnums.SegmentationRepresentations;
}): boolean {
return cstSegmentation.config.style.hasCustomStyle(specifier);
}
public getStyle = (specifier: {
viewportId: string;
segmentationId: string;
type: csToolsEnums.SegmentationRepresentations;
segmentIndex?: number;
}) => {
const style = cstSegmentation.config.style.getStyle(specifier);
return style;
};
public setStyle = (
specifier: {
type: csToolsEnums.SegmentationRepresentations;
viewportId?: string;
segmentationId?: string;
segmentIndex?: number;
},
style: cstTypes.LabelmapStyle | cstTypes.ContourStyle | cstTypes.SurfaceStyle,
merge: boolean = true
) => {
cstSegmentation.config.style.setStyle(specifier, style, merge);
this._broadcastEvent(EVENTS.SEGMENTATION_STYLE_MODIFIED, {
specifier,
style,
merge,
});
};
public resetToGlobalStyle = () => {
cstSegmentation.config.style.resetToGlobalStyle();
};
public getNextAvailableSegmentIndex(segmentationId: string): number {
const csSegmentation = this.getCornerstoneSegmentation(segmentationId);
// grab the next available segment index based on the object keys,
// so basically get the highest segment index value + 1
const segmentKeys = Object.keys(csSegmentation.segments);
return segmentKeys.length === 0 ? 1 : Math.max(...segmentKeys.map(Number)) + 1;
}
/**
* Adds a new segment to the specified segmentation.
* @param segmentationId - The ID of the segmentation to add the segment to.
* @param viewportId: The ID of the viewport to add the segment to, it is used to get the representation, if it is not
* provided, the first available representation for the segmentationId will be used.
* @param config - An object containing the configuration options for the new segment.
* - segmentIndex: (optional) The index of the segment to add. If not provided, the next available index will be used.
* - properties: (optional) An object containing the properties of the new segment.
* - label: (optional) The label of the new segment. If not provided, a default label will be used.
* - color: (optional) The color of the new segment in RGB format. If not provided, a default color will be used.
* - visibility: (optional) Whether the new segment should be visible. If not provided, the segment will be visible by default.
* - isLocked: (optional) Whether the new segment should be locked for editing. If not provided, the segment will not be locked by default.
* - active: (optional) Whether the new segment should be the active segment to be edited. If not provided, the segment will not be active by default.
*/
public addSegment(
segmentationId: string,
config: {
segmentIndex?: number;
label?: string;
isLocked?: boolean;
active?: boolean;
color?: csTypes.Color; // Add color type
visibility?: boolean; // Add visibility option
cachedStats?: Record<string, unknown>;