@cornerstonejs/adapters 5.11.6 → 5.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,10 @@
1
1
  import { utilities as utilities$1, normalizers, derivations, log } from 'dcmjs';
2
2
  import ndarray from 'ndarray';
3
3
  import getDatasetsFromImages from '../helpers/getDatasetsFromImages.js';
4
+ import { getValidOrientations, alignPixelDataWithSourceData } from './Segmentation_4X.js';
4
5
  import { utilities } from '@cornerstonejs/core';
5
6
 
6
7
  const cs3dLogger = utilities.logger.adaptersLog.getLogger('Cornerstone.Segmentation_3X');
7
- const _utilities$orientatio = utilities$1.orientation,
8
- rotateDirectionCosinesInPlane = _utilities$orientatio.rotateDirectionCosinesInPlane,
9
- flipIOP = _utilities$orientatio.flipImageOrientationPatient,
10
- flipMatrix2D = _utilities$orientatio.flipMatrix2D,
11
- rotateMatrix902D = _utilities$orientatio.rotateMatrix902D;
12
8
  const datasetToBlob = utilities$1.datasetToBlob,
13
9
  BitArray = utilities$1.BitArray,
14
10
  DicomMessage = utilities$1.DicomMessage,
@@ -316,80 +312,6 @@ function getImageIdOfReferencedFrame(sopInstanceUid, frameNumber, imageIds, meta
316
312
  });
317
313
  return imageId;
318
314
  }
319
-
320
- /**
321
- * getValidOrientations - returns an array of valid orientations.
322
- *
323
- * @param iop - The row (0..2) an column (3..5) direction cosines.
324
- * @return An array of valid orientations.
325
- */
326
- function getValidOrientations(iop) {
327
- const orientations = [];
328
-
329
- // [0, 1, 2]: 0, 0hf, 0vf
330
- // [3, 4, 5]: 90, 90hf, 90vf
331
- // [6, 7]: 180, 270
332
-
333
- orientations[0] = iop;
334
- orientations[1] = flipIOP.h(iop);
335
- orientations[2] = flipIOP.v(iop);
336
- const iop90 = rotateDirectionCosinesInPlane(iop, Math.PI / 2);
337
- orientations[3] = iop90;
338
- orientations[4] = flipIOP.h(iop90);
339
- orientations[5] = flipIOP.v(iop90);
340
- orientations[6] = rotateDirectionCosinesInPlane(iop, Math.PI);
341
- orientations[7] = rotateDirectionCosinesInPlane(iop, 1.5 * Math.PI);
342
- return orientations;
343
- }
344
-
345
- /**
346
- * alignPixelDataWithSourceData -
347
- *
348
- * @param pixelData2D - The data to align.
349
- * @param iop - The orientation of the image slice.
350
- * @param orientations - An array of valid imageOrientationPatient values.
351
- * @return The aligned pixelData.
352
- */
353
- function alignPixelDataWithSourceData(pixelData2D, iop, orientations) {
354
- if (compareIOP(iop, orientations[0])) {
355
- //Same orientation.
356
- return pixelData2D;
357
- } else if (compareIOP(iop, orientations[1])) {
358
- //Flipped vertically.
359
- return flipMatrix2D.v(pixelData2D);
360
- } else if (compareIOP(iop, orientations[2])) {
361
- //Flipped horizontally.
362
- return flipMatrix2D.h(pixelData2D);
363
- } else if (compareIOP(iop, orientations[3])) {
364
- //Rotated 90 degrees.
365
- return rotateMatrix902D(pixelData2D);
366
- } else if (compareIOP(iop, orientations[4])) {
367
- //Rotated 90 degrees and fliped horizontally.
368
- return flipMatrix2D.h(rotateMatrix902D(pixelData2D));
369
- } else if (compareIOP(iop, orientations[5])) {
370
- //Rotated 90 degrees and fliped vertically.
371
- return flipMatrix2D.v(rotateMatrix902D(pixelData2D));
372
- } else if (compareIOP(iop, orientations[6])) {
373
- //Rotated 180 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
374
- return rotateMatrix902D(rotateMatrix902D(pixelData2D));
375
- } else if (compareIOP(iop, orientations[7])) {
376
- //Rotated 270 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
377
- return rotateMatrix902D(rotateMatrix902D(rotateMatrix902D(pixelData2D)));
378
- }
379
- }
380
- const dx = 1e-5;
381
-
382
- /**
383
- * compareIOP - Returns true if iop1 and iop2 are equal
384
- * within a tollerance, dx.
385
- *
386
- * @param iop1 - An ImageOrientationPatient array.
387
- * @param iop2 - An ImageOrientationPatient array.
388
- * @return True if iop1 and iop2 are equal.
389
- */
390
- function compareIOP(iop1, iop2) {
391
- return Math.abs(iop1[0] - iop2[0]) < dx && Math.abs(iop1[1] - iop2[1]) < dx && Math.abs(iop1[2] - iop2[2]) < dx && Math.abs(iop1[3] - iop2[3]) < dx && Math.abs(iop1[4] - iop2[4]) < dx && Math.abs(iop1[5] - iop2[5]) < dx;
392
- }
393
315
  function getSegmentMetadata(multiframe) {
394
316
  const data = [];
395
317
  const segmentSequence = multiframe.SegmentSequence;
@@ -1,4 +1,5 @@
1
1
  export function generateSegmentation(images: object[], inputLabelmaps3D: any | any[], userOptions?: any): Blob;
2
+ export function getSegmentIndexForLabel(labelmap3D: any, labelValue: any): any;
2
3
  export function fillSegmentation(segmentation: any, inputLabelmaps3D: any, userOptions?: {}, images?: any[], metadata?: any): object;
3
4
  export function _getLabelmapsFromReferencedFrameIndicies(labelmap3D: any, referencedFrameIndicies: any): any[];
4
5
  export function _createSegFromImages(images: any[], isMultiframe: boolean, options: any): any;
@@ -12,8 +13,8 @@ export function getUnpackedChunks(data: any, maxBytesPerChunk: any): any[];
12
13
  export function getImageIdOfSourceImageBySourceImageSequence(SourceImageSequence: any, sopUIDImageIdIndexMap: any): string;
13
14
  export function getImageIdOfSourceImagebyGeometry(ReferencedSeriesInstanceUID: string, FrameOfReferenceUID: string, PerFrameFunctionalGroup: any, imageIds: string[], metadataProvider: any, tolerance: Float): string;
14
15
  export function getImageIdOfReferencedFrame(sopInstanceUid: string, frameNumber: number, sopUIDImageIdIndexMap: any): string;
15
- export function getValidOrientations(iop: any): any;
16
- export function alignPixelDataWithSourceData(pixelData2D: Ndarray, iop: any, orientations: any, tolerance: any): Ndarray;
16
+ export function getValidOrientations(iop: any | string): any;
17
+ export function alignPixelDataWithSourceData(pixelData2D: Ndarray, iop: any | string, orientations: any, tolerance: number): Ndarray | undefined;
17
18
  export function getSegmentMetadata(multiframe: any, seriesInstanceUid: any): {
18
19
  seriesInstanceUid: any;
19
20
  data: any[];
@@ -1,19 +1,16 @@
1
1
  import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
2
- import { utilities as utilities$1, data, normalizers, derivations, log } from 'dcmjs';
2
+ import { data, normalizers, derivations, utilities as utilities$1, log } from 'dcmjs';
3
3
  import ndarray from 'ndarray';
4
+ import { vec3 } from 'gl-matrix';
4
5
  import getDatasetsFromImages from '../helpers/getDatasetsFromImages.js';
5
6
  import checkOrientation from '../helpers/checkOrientation.js';
6
7
  import { utilities } from '@cornerstonejs/core';
8
+ import { utilities as utilities$2 } from '@cornerstonejs/metadata';
7
9
  import { getReferencedSourceImageSequenceItem, applyPerFrameFunctionalGroups } from '../Cornerstone3D/Segmentation/perFrameFunctionalGroups.js';
8
10
  import { getBitmapFramesFromDataset, encodeFramesToTransferSyntax, RLE_LOSSLESS_TRANSFER_SYNTAX_UID as RLE_LOSSLESS_TRANSFER_SYNTAX_UID$1 } from '../Cornerstone3D/encodePixelData.js';
9
11
  import { Events } from '../enums/Events.js';
10
12
 
11
13
  const cs3dLogger = utilities.logger.adaptersLog.getLogger('Cornerstone.Segmentation_4X');
12
- const _utilities$orientatio = utilities$1.orientation,
13
- rotateDirectionCosinesInPlane = _utilities$orientatio.rotateDirectionCosinesInPlane,
14
- flipIOP = _utilities$orientatio.flipImageOrientationPatient,
15
- flipMatrix2D = _utilities$orientatio.flipMatrix2D,
16
- rotateMatrix902D = _utilities$orientatio.rotateMatrix902D;
17
14
  const BitArray = data.BitArray,
18
15
  DicomMessage = data.DicomMessage,
19
16
  DicomMetaDictionary = data.DicomMetaDictionary;
@@ -54,6 +51,15 @@ function generateSegmentation(images, inputLabelmaps3D) {
54
51
  return fillSegmentation(segmentation, inputLabelmaps3D, userOptions);
55
52
  }
56
53
 
54
+ /**
55
+ * The segment index of a voxel value of one labelmap3D. A value that is not in
56
+ * `labelmap3D.labelToSegmentIndex` is its own segment index.
57
+ */
58
+ function getSegmentIndexForLabel(labelmap3D, labelValue) {
59
+ var _labelmap3D$labelToSe, _labelmap3D$labelToSe2;
60
+ return (_labelmap3D$labelToSe = labelmap3D === null || labelmap3D === void 0 || (_labelmap3D$labelToSe2 = labelmap3D.labelToSegmentIndex) === null || _labelmap3D$labelToSe2 === void 0 ? void 0 : _labelmap3D$labelToSe2[labelValue]) !== null && _labelmap3D$labelToSe !== void 0 ? _labelmap3D$labelToSe : labelValue;
61
+ }
62
+
57
63
  /**
58
64
  * The set of non-zero segment values actually present in a frame's pixel data,
59
65
  * collected in a single pass. `segmentsOnLabelmap` can be stale, so presence is
@@ -79,6 +85,12 @@ function segmentsPresentInFrame(pixelData) {
79
85
  *
80
86
  * @param segmentation - The segmentation object to be filled.
81
87
  * @param inputLabelmaps3D - An array of 3D labelmaps, or a single 3D labelmap.
88
+ * The voxels of a labelmap3D hold label values. `labelToSegmentIndex` maps a
89
+ * label value to its segment index, for a layer that stores a segment under
90
+ * another label value; a value that is not in the map is its own segment
91
+ * index. `segmentsOnLabelmap` of each labelmap2D lists label values. Two
92
+ * label values with the same segment index, in one labelmap3D or in two,
93
+ * give one SEG segment.
82
94
  * @param userOptions - Optional configuration settings. Will override the default options.
83
95
  * - `transferSyntaxUid` — the output transfer syntax. Defaults to RLE Lossless
84
96
  * (`1.2.840.10008.1.2.5`); Explicit VR Little Endian
@@ -92,7 +104,7 @@ function segmentsPresentInFrame(pixelData) {
92
104
  * @returns {object} The filled segmentation object.
93
105
  */
94
106
  function fillSegmentation(segmentation, inputLabelmaps3D) {
95
- var _ref, _options$transferSynt;
107
+ var _segmentation$dataset, _segmentation$dataset2, _ref, _options$transferSynt;
96
108
  let userOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
97
109
  let images = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
98
110
  let metadata = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
@@ -100,79 +112,68 @@ function fillSegmentation(segmentation, inputLabelmaps3D) {
100
112
 
101
113
  // Use another variable so we don't redefine labelmaps3D.
102
114
  const labelmaps3D = Array.isArray(inputLabelmaps3D) ? inputLabelmaps3D : [inputLabelmaps3D];
103
- const referencedFramesPerLabelmap = [];
104
115
  const frameDescriptors = [];
116
+ const entriesBySegmentIndex = new Map();
105
117
  for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
106
118
  const labelmap3D = labelmaps3D[labelmapIndex];
107
119
  const labelmaps2D = labelmap3D.labelmaps2D,
108
120
  segmentMetadata = labelmap3D.metadata;
109
- const referencedFramesPerSegment = [];
110
- for (let i = 1; i < segmentMetadata.length; i++) {
111
- if (segmentMetadata[i]) {
112
- referencedFramesPerSegment[i] = [];
113
- }
114
- }
115
121
  for (let i = 0; i < labelmaps2D.length; i++) {
116
122
  const labelmap2D = labelmaps2D[i];
117
- if (!(labelmap2D !== null && labelmap2D !== void 0 && labelmap2D.pixelData)) {
123
+ if (!labelmap2D) {
118
124
  continue;
119
125
  }
120
126
  const segmentsOnLabelmap = labelmap2D.segmentsOnLabelmap;
121
- const presentSegments = segmentsPresentInFrame(labelmap2D.pixelData);
122
- segmentsOnLabelmap.forEach(segmentIndex => {
123
- if (segmentIndex !== 0 && segmentMetadata[segmentIndex] && referencedFramesPerSegment[segmentIndex] && presentSegments.has(segmentIndex)) {
124
- referencedFramesPerSegment[segmentIndex].push(i);
127
+ segmentsPresentInFrame(labelmap2D.pixelData).forEach(labelValue => {
128
+ const segmentIndex = getSegmentIndexForLabel(labelmap3D, labelValue);
129
+ if (!segmentMetadata[segmentIndex] || !segmentsOnLabelmap.includes(labelValue)) {
130
+ return;
131
+ }
132
+ if (!entriesBySegmentIndex.has(segmentIndex)) {
133
+ entriesBySegmentIndex.set(segmentIndex, {
134
+ segmentIndex,
135
+ metadata: segmentMetadata[segmentIndex],
136
+ sources: [],
137
+ frameIndices: new Set()
138
+ });
139
+ }
140
+ const entry = entriesBySegmentIndex.get(segmentIndex);
141
+ if (!entry.sources.some(source => source.labelmap3D === labelmap3D && source.labelValue === labelValue)) {
142
+ entry.sources.push({
143
+ labelmap3D,
144
+ labelValue
145
+ });
125
146
  }
147
+ entry.frameIndices.add(i);
126
148
  });
127
149
  }
128
- referencedFramesPerLabelmap[labelmapIndex] = referencedFramesPerSegment;
129
- }
130
- let numberOfFrames = 0;
131
- for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
132
- const referencedFramesPerSegment = referencedFramesPerLabelmap[labelmapIndex];
133
- const labelmap3D = labelmaps3D[labelmapIndex];
134
- const segmentMetadata = labelmap3D.metadata;
135
- for (let segmentIndex = 1; segmentIndex < referencedFramesPerSegment.length; segmentIndex++) {
136
- const referencedFrameIndicies = referencedFramesPerSegment[segmentIndex];
137
- if (!(referencedFrameIndicies !== null && referencedFrameIndicies !== void 0 && referencedFrameIndicies.length) || !segmentMetadata[segmentIndex]) {
138
- continue;
139
- }
140
- const labelmaps = _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies);
141
- if (!labelmaps.length || !labelmaps.some(frame => (frame === null || frame === void 0 ? void 0 : frame.length) && frame.some(v => v !== 0))) {
142
- continue;
143
- }
144
- numberOfFrames += referencedFrameIndicies.length;
145
- }
146
150
  }
151
+
152
+ // dcmjs numbers the segments in the order they are added.
153
+ const segmentEntries = [...entriesBySegmentIndex.values()].sort((a, b) => a.segmentIndex - b.segmentIndex);
154
+ const numberOfFrames = segmentEntries.reduce((total, entry) => total + entry.frameIndices.size, 0);
147
155
  if (numberOfFrames === 0) {
148
156
  throw new Error('No non-empty segmentation frames found for SEG export');
149
157
  }
150
158
  segmentation.setNumberOfFrames(numberOfFrames);
151
- for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
152
- const referencedFramesPerSegment = referencedFramesPerLabelmap[labelmapIndex];
153
- const labelmap3D = labelmaps3D[labelmapIndex];
154
- const segmentMetadata = labelmap3D.metadata;
155
- for (let segmentIndex = 1; segmentIndex < referencedFramesPerSegment.length; segmentIndex++) {
156
- const referencedFrameIndicies = referencedFramesPerSegment[segmentIndex];
157
- if (!(referencedFrameIndicies !== null && referencedFrameIndicies !== void 0 && referencedFrameIndicies.length) || !segmentMetadata[segmentIndex]) {
158
- continue;
159
- }
160
- const labelmaps = _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies);
161
- if (!labelmaps.length || !labelmaps.some(frame => (frame === null || frame === void 0 ? void 0 : frame.length) && frame.some(v => v !== 0))) {
162
- continue;
163
- }
164
-
165
- // Frame numbers start from 1.
166
- const referencedFrameNumbers = referencedFrameIndicies.map(element => element + 1);
167
- referencedFrameNumbers.forEach(frameNumber => {
168
- frameDescriptors.push({
169
- referencedSegmentNumber: segmentIndex,
170
- sourceFrameIndex: frameNumber - 1
171
- });
159
+ const firstSegmentNumber = ((_segmentation$dataset = (_segmentation$dataset2 = segmentation.dataset.SegmentSequence) === null || _segmentation$dataset2 === void 0 ? void 0 : _segmentation$dataset2.length) !== null && _segmentation$dataset !== void 0 ? _segmentation$dataset : 0) + 1;
160
+ segmentEntries.forEach((entry, entryIndex) => {
161
+ const referencedFrameIndicies = [...entry.frameIndices].sort((a, b) => a - b);
162
+ const _getSegmentLabelmaps2 = _getSegmentLabelmaps(entry.sources, referencedFrameIndicies),
163
+ labelmaps = _getSegmentLabelmaps2.labelmaps,
164
+ labelValue = _getSegmentLabelmaps2.labelValue;
165
+
166
+ // Frame numbers start from 1.
167
+ const referencedFrameNumbers = referencedFrameIndicies.map(element => element + 1);
168
+ segmentation.addSegmentFromLabelmap(entry.metadata, labelmaps, labelValue, referencedFrameNumbers);
169
+ const referencedSegmentNumber = firstSegmentNumber + entryIndex;
170
+ referencedFrameNumbers.forEach(frameNumber => {
171
+ frameDescriptors.push({
172
+ referencedSegmentNumber,
173
+ sourceFrameIndex: frameNumber - 1
172
174
  });
173
- segmentation.addSegmentFromLabelmap(segmentMetadata[segmentIndex], labelmaps, segmentIndex, referencedFrameNumbers);
174
- }
175
- }
175
+ });
176
+ });
176
177
  if (frameDescriptors.length && images !== null && images !== void 0 && images.length && metadata) {
177
178
  // Every SEG frame must reference a resolvable source SOP Instance UID.
178
179
  // Reject rather than silently dropping frames: a dropped frame would make
@@ -251,6 +252,48 @@ function fillSegmentation(segmentation, inputLabelmaps3D) {
251
252
  }
252
253
  return segmentation;
253
254
  }
255
+
256
+ /**
257
+ * The frames of one SEG segment and the value that marks the segment in them.
258
+ * A segment with one source uses the frames of its labelmap3D. A segment with
259
+ * more sources gets new binary frames, with 1 where any source has its label
260
+ * value.
261
+ */
262
+ function _getSegmentLabelmaps(sources, referencedFrameIndicies) {
263
+ if (sources.length === 1) {
264
+ const _sources = _slicedToArray(sources, 1),
265
+ _sources$ = _sources[0],
266
+ labelmap3D = _sources$.labelmap3D,
267
+ labelValue = _sources$.labelValue;
268
+ return {
269
+ labelmaps: _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies),
270
+ labelValue
271
+ };
272
+ }
273
+ const labelmaps = referencedFrameIndicies.map(frameIndex => {
274
+ let merged;
275
+ sources.forEach(_ref2 => {
276
+ var _labelmap3D$labelmaps;
277
+ let labelmap3D = _ref2.labelmap3D,
278
+ labelValue = _ref2.labelValue;
279
+ const pixelData = (_labelmap3D$labelmaps = labelmap3D.labelmaps2D[frameIndex]) === null || _labelmap3D$labelmaps === void 0 ? void 0 : _labelmap3D$labelmaps.pixelData;
280
+ if (!pixelData) {
281
+ return;
282
+ }
283
+ merged || (merged = new Uint8Array(pixelData.length));
284
+ for (let i = 0; i < pixelData.length; i++) {
285
+ if (pixelData[i] === labelValue) {
286
+ merged[i] = 1;
287
+ }
288
+ }
289
+ });
290
+ return merged;
291
+ });
292
+ return {
293
+ labelmaps,
294
+ labelValue: 1
295
+ };
296
+ }
254
297
  function _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies) {
255
298
  const labelmaps2D = labelmap3D.labelmaps2D;
256
299
  const labelmaps = [];
@@ -690,9 +733,9 @@ function checkSEGsOverlapping(pixelData, multiframe, imageIds, validOrientations
690
733
  frameSegmentsMapping.set(imageIdIndex, [frameSegment]);
691
734
  }
692
735
  }
693
- for (let _ref2 of frameSegmentsMapping.entries()) {
694
- var _ref3 = _slicedToArray(_ref2, 2);
695
- let role = _ref3[1];
736
+ for (let _ref3 of frameSegmentsMapping.entries()) {
737
+ var _ref4 = _slicedToArray(_ref3, 2);
738
+ let role = _ref4[1];
696
739
  let temp2DArray = new TypedArrayConstructor(sliceLength).fill(0);
697
740
  for (let i = 0; i < role.length; ++i) {
698
741
  const frameSegment = role[i];
@@ -773,7 +816,9 @@ function insertOverlappingPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray,
773
816
  continue;
774
817
  }
775
818
  const sourceImageMetadata = metadataProvider.get('instance', imageId);
776
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
819
+ // Compare the aligned frame: a frame rotated by 90 degrees in-plane has
820
+ // its Rows and Columns swapped relative to the source image.
821
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
777
822
  throw new Error('Individual SEG frames have different geometry dimensions (Rows and Columns) ' + 'respect to the source image reference frame. This is not yet supported. ' + 'Aborting segmentation loading. ');
778
823
  }
779
824
  const imageIdIndex = imageIds.findIndex(element => element === imageId);
@@ -885,7 +930,7 @@ function insertPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray, labelmapBu
885
930
  continue;
886
931
  }
887
932
  const sourceImageMetadata = imageIdMaps.metadata[imageId];
888
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
933
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
889
934
  throw new Error('Individual SEG frames have different geometry dimensions (Rows and Columns) ' + 'respect to the source image reference frame. This is not yet supported. ' + 'Aborting segmentation loading. ');
890
935
  }
891
936
  const imageIdIndex = imageIdMaps.indices[imageId];
@@ -1049,6 +1094,12 @@ function isMultiframeImage(imageMetadata) {
1049
1094
  /**
1050
1095
  * getImageIdOfSourceImagebyGeometry - Returns the Cornerstone imageId of the source image.
1051
1096
  *
1097
+ * The lookup first matches the SEG frame position exactly with the source
1098
+ * image position. If no image matches, the lookup selects the source image
1099
+ * whose plane holds the SEG frame position. A SEG frame that is flipped or
1100
+ * rotated in-plane has its origin at a different corner of the source slice,
1101
+ * so only the plane match finds that frame.
1102
+ *
1052
1103
  * @param {String} ReferencedSeriesInstanceUID Referenced series of the source image.
1053
1104
  * @param {String} FrameOfReferenceUID Frame of reference.
1054
1105
  * @param {Object} PerFrameFunctionalGroup Sequence describing segmentation reference attributes per frame.
@@ -1063,25 +1114,43 @@ function getImageIdOfSourceImagebyGeometry(ReferencedSeriesInstanceUID, FrameOfR
1063
1114
  if (!ReferencedSeriesInstanceUID || !((_PerFrameFunctionalGr = PerFrameFunctionalGroup.PlanePositionSequence) !== null && _PerFrameFunctionalGr !== void 0 && (_PerFrameFunctionalGr = _PerFrameFunctionalGr[0]) !== null && _PerFrameFunctionalGr !== void 0 && _PerFrameFunctionalGr.ImagePositionPatient)) {
1064
1115
  return undefined;
1065
1116
  }
1066
- const segFramePosition = PerFrameFunctionalGroup.PlanePositionSequence[0].ImagePositionPatient;
1117
+ const segFramePosition = utilities$2.toNumber(PerFrameFunctionalGroup.PlanePositionSequence[0].ImagePositionPatient);
1118
+ const candidates = [];
1067
1119
  for (let imageId of imageIds) {
1068
1120
  const sourceImageMetadata = metadataProvider.get('instance', imageId);
1069
1121
  if (!sourceImageMetadata) {
1070
1122
  continue;
1071
1123
  }
1072
- const isMultiframe = isMultiframeImage(sourceImageMetadata);
1073
1124
  if (!sourceImageMetadata.ImagePositionPatient || sourceImageMetadata.FrameOfReferenceUID !== FrameOfReferenceUID || sourceImageMetadata.SeriesInstanceUID !== ReferencedSeriesInstanceUID) {
1074
1125
  continue;
1075
1126
  }
1076
-
1127
+ const imagePlane = metadataProvider.get('imagePlaneModule', imageId);
1077
1128
  // For multiframe images, check each frame's position
1078
- if (isMultiframe) {
1079
- var _metadataProvider$get2;
1080
- const framePosition = (_metadataProvider$get2 = metadataProvider.get('imagePlaneModule', imageId)) === null || _metadataProvider$get2 === void 0 ? void 0 : _metadataProvider$get2.imagePositionPatient;
1081
- if (framePosition && utilities.isEqual(segFramePosition, framePosition, tolerance)) {
1082
- return imageId;
1083
- }
1084
- } else if (utilities.isEqual(segFramePosition, sourceImageMetadata.ImagePositionPatient, tolerance)) {
1129
+ const position = utilities$2.toNumber(isMultiframeImage(sourceImageMetadata) ? imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.imagePositionPatient : sourceImageMetadata.ImagePositionPatient);
1130
+ if (!position) {
1131
+ continue;
1132
+ }
1133
+ if (utilities.isEqual(segFramePosition, position, tolerance)) {
1134
+ return imageId;
1135
+ }
1136
+ candidates.push({
1137
+ imageId,
1138
+ position,
1139
+ imagePlane
1140
+ });
1141
+ }
1142
+ for (const _ref5 of candidates) {
1143
+ const imageId = _ref5.imageId;
1144
+ const position = _ref5.position;
1145
+ const imagePlane = _ref5.imagePlane;
1146
+ const rowCosines = utilities$2.toNumber(imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.rowCosines);
1147
+ const columnCosines = utilities$2.toNumber(imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.columnCosines);
1148
+ if (!rowCosines || !columnCosines) {
1149
+ continue;
1150
+ }
1151
+ const normal = vec3.cross([0, 0, 0], rowCosines, columnCosines);
1152
+ const distance = utilities.voxelSlab.signedDistanceToPlane(segFramePosition, position, normal);
1153
+ if (Math.abs(distance) < tolerance) {
1085
1154
  return imageId;
1086
1155
  }
1087
1156
  }
@@ -1089,77 +1158,129 @@ function getImageIdOfSourceImagebyGeometry(ReferencedSeriesInstanceUID, FrameOfR
1089
1158
  }
1090
1159
 
1091
1160
  /**
1092
- * getValidOrientations - returns an array of valid orientations.
1161
+ * getValidOrientations - returns the 8 in-plane orientations of a source
1162
+ * image, as the row (r) and column (c) cosines of a SEG frame in that plane.
1093
1163
  *
1094
- * @param {Number[6]} iop The row (0..2) an column (3..5) direction cosines.
1095
- * @return {Number[8][6]} An array of valid orientations.
1164
+ * | Index | SEG IOP | SEG frame relative to the source |
1165
+ * | ----- | ---------- | -------------------------------- |
1166
+ * | 0 | (r, c) | identity |
1167
+ * | 1 | (r, -c) | flipped vertically |
1168
+ * | 2 | (-r, c) | flipped horizontally |
1169
+ * | 3 | (c, -r) | rotated 90 degrees |
1170
+ * | 4 | (c, r) | transposed |
1171
+ * | 5 | (-c, -r) | anti-transposed |
1172
+ * | 6 | (-r, -c) | rotated 180 degrees |
1173
+ * | 7 | (-c, r) | rotated 270 degrees |
1174
+ *
1175
+ * The list is built from the cosines directly: dcmjs
1176
+ * rotateDirectionCosinesInPlane negates its result, so it never yields the
1177
+ * 180 degree orientation. See
1178
+ * https://github.com/cornerstonejs/cornerstone3D/issues/2959
1179
+ *
1180
+ * @param {Number[6]|String[6]} iop The row (0..2) and column (3..5) direction
1181
+ * cosines. DS strings are converted to numbers.
1182
+ * @return {Number[8][6]} The valid orientations, in the order of the table.
1096
1183
  */
1097
1184
  function getValidOrientations(iop) {
1098
- const orientations = [];
1099
-
1100
- // [0, 1, 2]: 0, 0hf, 0vf
1101
- // [3, 4, 5]: 90, 90hf, 90vf
1102
- // [6, 7]: 180, 270
1103
-
1104
- orientations[0] = iop;
1105
- orientations[1] = flipIOP.h(iop);
1106
- orientations[2] = flipIOP.v(iop);
1107
- const iop90 = rotateDirectionCosinesInPlane(iop, Math.PI / 2);
1108
- orientations[3] = iop90;
1109
- orientations[4] = flipIOP.h(iop90);
1110
- orientations[5] = flipIOP.v(iop90);
1111
- orientations[6] = rotateDirectionCosinesInPlane(iop, Math.PI);
1112
- orientations[7] = rotateDirectionCosinesInPlane(iop, 1.5 * Math.PI);
1113
- return orientations;
1185
+ const numericIop = utilities$2.toNumber(iop);
1186
+ const r = numericIop.slice(0, 3);
1187
+ const c = numericIop.slice(3, 6);
1188
+ const negR = vec3.negate([0, 0, 0], r);
1189
+ const negC = vec3.negate([0, 0, 0], c);
1190
+ return [[...r, ...c], [...r, ...negC], [...negR, ...c], [...c, ...negR], [...c, ...r], [...negC, ...negR], [...negR, ...negC], [...negC, ...r]];
1114
1191
  }
1115
1192
 
1116
1193
  /**
1117
- * alignPixelDataWithSourceData -
1194
+ * The pixel operation that aligns a SEG frame with its source image, per entry
1195
+ * of getValidOrientations. The aligned pixel (a, b) reads the SEG pixel (i, j),
1196
+ * where (i, j) is (a, b), or (b, a) when `transpose` is set, and then
1197
+ * `flipRows` and `flipColumns` mirror i and j.
1198
+ */
1199
+ const ORIENTATION_ALIGNMENTS = [{
1200
+ transpose: false,
1201
+ flipRows: false,
1202
+ flipColumns: false
1203
+ }, {
1204
+ transpose: false,
1205
+ flipRows: true,
1206
+ flipColumns: false
1207
+ }, {
1208
+ transpose: false,
1209
+ flipRows: false,
1210
+ flipColumns: true
1211
+ }, {
1212
+ transpose: true,
1213
+ flipRows: true,
1214
+ flipColumns: false
1215
+ }, {
1216
+ transpose: true,
1217
+ flipRows: false,
1218
+ flipColumns: false
1219
+ }, {
1220
+ transpose: true,
1221
+ flipRows: true,
1222
+ flipColumns: true
1223
+ }, {
1224
+ transpose: false,
1225
+ flipRows: true,
1226
+ flipColumns: true
1227
+ }, {
1228
+ transpose: true,
1229
+ flipRows: false,
1230
+ flipColumns: true
1231
+ }];
1232
+
1233
+ /**
1234
+ * alignPixelDataWithSourceData - finds the orientation of a SEG frame in the
1235
+ * list from getValidOrientations, and returns the frame in the pixel order of
1236
+ * the source image.
1237
+ *
1238
+ * The result keeps the typed array type of the input, so 16-bit LABELMAP
1239
+ * values are not truncated. A frame that is not aligned already is copied in
1240
+ * one pass.
1118
1241
  *
1119
- * @param {Ndarray} pixelData2D - The data to align.
1120
- * @param {Number[6]} iop - The orientation of the image slice.
1121
- * @param {Number[8][6]} orientations - An array of valid imageOrientationPatient values.
1122
- * @param {Number} tolerance.
1123
- * @return {Ndarray} The aligned pixelData.
1242
+ * @param {Ndarray} pixelData2D - The SEG frame, with shape [Rows, Columns].
1243
+ * @param {Number[6]|String[6]} iop - The orientation of the SEG frame. DS
1244
+ * strings are converted to numbers.
1245
+ * @param {Number[8][6]} orientations - The result of getValidOrientations.
1246
+ * @param {Number} tolerance - The tolerance of the IOP comparison.
1247
+ * @return {Ndarray|undefined} The aligned frame, with shape
1248
+ * [source Rows, source Columns], or undefined when the frame is not in-plane.
1124
1249
  */
1125
1250
  function alignPixelDataWithSourceData(pixelData2D, iop, orientations, tolerance) {
1126
- if (utilities.isEqual(iop, orientations[0], tolerance)) {
1251
+ const numericIop = utilities$2.toNumber(iop);
1252
+ const index = orientations.findIndex(orientation => utilities.isEqual(numericIop, orientation, tolerance));
1253
+ if (index === -1) {
1254
+ return undefined;
1255
+ }
1256
+ if (index === 0) {
1127
1257
  return pixelData2D;
1128
- } else if (utilities.isEqual(iop, orientations[1], tolerance)) {
1129
- // Flipped vertically.
1130
-
1131
- // Undo Flip
1132
- return flipMatrix2D.v(pixelData2D);
1133
- } else if (utilities.isEqual(iop, orientations[2], tolerance)) {
1134
- // Flipped horizontally.
1135
-
1136
- // Unfo flip
1137
- return flipMatrix2D.h(pixelData2D);
1138
- } else if (utilities.isEqual(iop, orientations[3], tolerance)) {
1139
- //Rotated 90 degrees
1140
-
1141
- // Rotate back
1142
- return rotateMatrix902D(pixelData2D);
1143
- } else if (utilities.isEqual(iop, orientations[4], tolerance)) {
1144
- //Rotated 90 degrees and fliped horizontally.
1145
-
1146
- // Undo flip and rotate back.
1147
- return rotateMatrix902D(flipMatrix2D.h(pixelData2D));
1148
- } else if (utilities.isEqual(iop, orientations[5], tolerance)) {
1149
- // Rotated 90 degrees and fliped vertically
1150
-
1151
- // Unfo flip and rotate back.
1152
- return rotateMatrix902D(flipMatrix2D.v(pixelData2D));
1153
- } else if (utilities.isEqual(iop, orientations[6], tolerance)) {
1154
- // Rotated 180 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
1155
-
1156
- return rotateMatrix902D(rotateMatrix902D(pixelData2D));
1157
- } else if (utilities.isEqual(iop, orientations[7], tolerance)) {
1158
- // Rotated 270 degrees
1159
-
1160
- // Rotate back.
1161
- return rotateMatrix902D(rotateMatrix902D(rotateMatrix902D(pixelData2D)));
1162
1258
  }
1259
+ const _ORIENTATION_ALIGNMEN = ORIENTATION_ALIGNMENTS[index],
1260
+ transpose = _ORIENTATION_ALIGNMEN.transpose,
1261
+ flipRows = _ORIENTATION_ALIGNMEN.flipRows,
1262
+ flipColumns = _ORIENTATION_ALIGNMEN.flipColumns;
1263
+ const _pixelData2D$shape = _slicedToArray(pixelData2D.shape, 2),
1264
+ rows = _pixelData2D$shape[0],
1265
+ columns = _pixelData2D$shape[1];
1266
+ const alignedRows = transpose ? columns : rows;
1267
+ const alignedColumns = transpose ? rows : columns;
1268
+ const TypedArrayConstructor = pixelData2D.data.constructor;
1269
+ const aligned = ndarray(new TypedArrayConstructor(rows * columns), [alignedRows, alignedColumns]);
1270
+ for (let a = 0; a < alignedRows; a++) {
1271
+ for (let b = 0; b < alignedColumns; b++) {
1272
+ let i = transpose ? b : a;
1273
+ let j = transpose ? a : b;
1274
+ if (flipRows) {
1275
+ i = rows - 1 - i;
1276
+ }
1277
+ if (flipColumns) {
1278
+ j = columns - 1 - j;
1279
+ }
1280
+ aligned.set(a, b, pixelData2D.get(i, j));
1281
+ }
1282
+ }
1283
+ return aligned;
1163
1284
  }
1164
1285
  function getSegmentMetadata(multiframe, seriesInstanceUid) {
1165
1286
  const segmentSequence = multiframe.SegmentSequence;
@@ -1259,10 +1380,10 @@ function calculateCentroid(imageIdIndexBufferIndex, multiframe, metadataProvider
1259
1380
  let worldYAcc = 0;
1260
1381
  let worldZAcc = 0;
1261
1382
  let count = 0;
1262
- for (const _ref4 of Object.entries(imageIdIndexBufferIndex)) {
1263
- var _ref5 = _slicedToArray(_ref4, 2);
1264
- const imageIdIndex = _ref5[0];
1265
- const bufferIndices = _ref5[1];
1383
+ for (const _ref6 of Object.entries(imageIdIndexBufferIndex)) {
1384
+ var _ref7 = _slicedToArray(_ref6, 2);
1385
+ const imageIdIndex = _ref7[0];
1386
+ const bufferIndices = _ref7[1];
1266
1387
  const z = Number(imageIdIndex);
1267
1388
  if (!bufferIndices || bufferIndices.length === 0) {
1268
1389
  continue;
@@ -1320,4 +1441,4 @@ const Segmentation = {
1320
1441
  fillSegmentation
1321
1442
  };
1322
1443
 
1323
- export { _createSegFromImages, _getLabelmapsFromReferencedFrameIndicies, alignPixelDataWithSourceData, calculateCentroid, checkSEGsOverlapping, Segmentation as default, fillSegmentation, findReferenceSourceImageId, generateSegmentation, generateToolState, getImageIdOfSourceImageBySourceImageSequence, getImageIdOfSourceImagebyGeometry, getSegmentIndex, getSegmentMetadata, getUnpackedChunks, getUnpackedOffsetAndLength, getValidOrientations, insertOverlappingPixelDataPlanar, insertPixelDataPlanar, readFromUnpackedChunks, unpackPixelData };
1444
+ export { _createSegFromImages, _getLabelmapsFromReferencedFrameIndicies, alignPixelDataWithSourceData, calculateCentroid, checkSEGsOverlapping, Segmentation as default, fillSegmentation, findReferenceSourceImageId, generateSegmentation, generateToolState, getImageIdOfSourceImageBySourceImageSequence, getImageIdOfSourceImagebyGeometry, getSegmentIndex, getSegmentIndexForLabel, getSegmentMetadata, getUnpackedChunks, getUnpackedOffsetAndLength, getValidOrientations, insertOverlappingPixelDataPlanar, insertPixelDataPlanar, readFromUnpackedChunks, unpackPixelData };
@@ -2,7 +2,7 @@ import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
2
2
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
3
3
  import { normalizers, derivations } from 'dcmjs';
4
4
  import { utilities, Enums } from '@cornerstonejs/core';
5
- import { fillSegmentation } from '../../Cornerstone/Segmentation_4X.js';
5
+ import { fillSegmentation, getSegmentIndexForLabel } from '../../Cornerstone/Segmentation_4X.js';
6
6
  import { getBitmapFramesFromDataset, encodeFramesToTransferSyntax, EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID } from '../encodePixelData.js';
7
7
  import { normalizeSharedFunctionalGroupsSequence, getReferencedSourceImageSequenceItem, applyPerFrameFunctionalGroups } from './perFrameFunctionalGroups.js';
8
8
 
@@ -84,8 +84,9 @@ function maxSegmentValue(labelmap3DArray, frameIndices) {
84
84
  return;
85
85
  }
86
86
  for (let i = 0; i < pixelData.length; i++) {
87
- if (pixelData[i] > max) {
88
- max = pixelData[i];
87
+ const segmentIndex = pixelData[i] ? getSegmentIndexForLabel(labelmap3D, pixelData[i]) : 0;
88
+ if (segmentIndex > max) {
89
+ max = segmentIndex;
89
90
  }
90
91
  }
91
92
  });
@@ -171,10 +172,10 @@ function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, imag
171
172
  }
172
173
  const len = Math.min(source.length, frameLength);
173
174
  for (let i = 0; i < len; i++) {
174
- const value = source[i];
175
- if (value === 0) {
175
+ if (source[i] === 0) {
176
176
  continue;
177
177
  }
178
+ const value = getSegmentIndexForLabel(labelmap3D, source[i]);
178
179
  if (frame[i] !== 0 && frame[i] !== value && !overlapWarned) {
179
180
  cs3dLogger.warn('generateSegmentation: overlapping labelmap segments detected on the ' + 'same voxel while exporting a LABELMAP SEG; the later labelmap wins.');
180
181
  overlapWarned = true;
@@ -309,6 +310,7 @@ function _createMultiframeSegmentationFromReferencedImages(images, metadata, opt
309
310
  const seriesData = metadata.get(MetadataModules.SERIES_DATA, imageId);
310
311
  const imageData = metadata.get(MetadataModules.IMAGE_DATA, imageId);
311
312
  return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, studyData), seriesData), imageData), {}, {
313
+ NumberOfFrames: 1,
312
314
  PixelData: image.voxelManager.getScalarData(),
313
315
  BitsAllocated: 16,
314
316
  _vrMap: {
@@ -598,7 +598,7 @@ function insertPixelDataPlanar(_ref0) {
598
598
  cs3dLogger.warn("No instance metadata for referenced image at frame : ".concat(i, "."));
599
599
  continue;
600
600
  }
601
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
601
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
602
602
  throw new Error('Individual SEG frames have different geometry dimensions (Rows and Columns) ' + 'respect to the source image reference frame. This is not yet supported. ' + 'Aborting segmentation loading. ');
603
603
  }
604
604
  const imageIdIndex = imageIdMaps.indices[stackImageId];
@@ -692,7 +692,7 @@ function insertPixelDataPlanar(_ref0) {
692
692
  cs3dLogger.warn("No instance metadata for referenced image at frame : ".concat(i, "."));
693
693
  continue;
694
694
  }
695
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
695
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
696
696
  throw new Error('Individual Labelmap SEG frames have different geometry dimensions (Rows and Columns) ' + 'respect to the source image reference frame. This is not yet supported. ' + 'Aborting segmentation loading. ');
697
697
  }
698
698
  const imageIdIndex = imageIdMaps.indices[stackImageId];
@@ -951,8 +951,8 @@ const getSegmentData = _ref14 => {
951
951
  });
952
952
  checkImageDimensions({
953
953
  metadataProvider,
954
- Rows,
955
- Columns,
954
+ Rows: alignedPixelDataI.shape[0],
955
+ Columns: alignedPixelDataI.shape[1],
956
956
  imageId: referencedImageId
957
957
  });
958
958
  const indexCache = [];
@@ -1 +1 @@
1
- export declare const version = "5.11.6";
1
+ export declare const version = "5.12.0";
@@ -1,3 +1,3 @@
1
- const version = '5.11.6';
1
+ const version = '5.12.0';
2
2
 
3
3
  export { version };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cornerstonejs/adapters",
3
- "version": "5.11.6",
3
+ "version": "5.12.0",
4
4
  "description": "Adapters for Cornerstone3D to/from formats including DICOM SR and others",
5
5
  "module": "./dist/esm/index.js",
6
6
  "types": "./dist/esm/index.d.ts",
@@ -99,13 +99,13 @@
99
99
  "ndarray": "1.0.19"
100
100
  },
101
101
  "devDependencies": {
102
- "@cornerstonejs/core": "5.11.6",
103
- "@cornerstonejs/metadata": "5.11.6",
104
- "@cornerstonejs/tools": "5.11.6"
102
+ "@cornerstonejs/core": "5.12.0",
103
+ "@cornerstonejs/metadata": "5.12.0",
104
+ "@cornerstonejs/tools": "5.12.0"
105
105
  },
106
106
  "peerDependencies": {
107
- "@cornerstonejs/core": "5.11.6",
108
- "@cornerstonejs/metadata": "5.11.6",
109
- "@cornerstonejs/tools": "5.11.6"
107
+ "@cornerstonejs/core": "5.12.0",
108
+ "@cornerstonejs/metadata": "5.12.0",
109
+ "@cornerstonejs/tools": "5.12.0"
110
110
  }
111
111
  }