@cornerstonejs/adapters 5.11.7 → 5.12.1

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,19 +1,31 @@
1
+ import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
1
2
  import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
2
3
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
3
- import { normalizers, derivations } from 'dcmjs';
4
- import { utilities, Enums } from '@cornerstonejs/core';
5
- import { fillSegmentation } from '../../Cornerstone/Segmentation_4X.js';
4
+ import { normalizers, derivations, data } from 'dcmjs';
5
+ import { utilities as utilities$1, Enums } from '@cornerstonejs/core';
6
+ import { fillSegmentation, getSegmentIndexForLabel } from '../../Cornerstone/Segmentation_4X.js';
6
7
  import { getBitmapFramesFromDataset, encodeFramesToTransferSyntax, EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID } from '../encodePixelData.js';
7
- import { normalizeSharedFunctionalGroupsSequence, getReferencedSourceImageSequenceItem, applyPerFrameFunctionalGroups } from './perFrameFunctionalGroups.js';
8
+ import { normalizeSharedFunctionalGroupsSequence, getReferencedSourceImageSequenceItem, applyPerFrameFunctionalGroups, setPlaneOrientations } from './perFrameFunctionalGroups.js';
9
+ import { utilities } from '@cornerstonejs/metadata';
10
+ import { vec3 } from 'gl-matrix';
11
+ import { toArray } from '../../helpers/toArray.js';
12
+ import { getSourceFrame, sliceNormal, GEOMETRY_TOLERANCE, toFiniteVector } from './sourceFrame.js';
8
13
 
14
+ const _excluded = ["SliceThickness", "SpacingBetweenSlices"];
9
15
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
10
16
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
11
- const cs3dLogger = utilities.logger.adaptersLog.getLogger('Cornerstone3D.Segmentation.generateSegmentation');
17
+ const isEqual = utilities.isEqual;
18
+ const cs3dLogger = utilities$1.logger.adaptersLog.getLogger('Cornerstone3D.Segmentation.generateSegmentation');
12
19
  const MetadataModules = Enums.MetadataModules;
13
20
  const SEGImageNormalizer = normalizers.SEGImageNormalizer;
14
21
  const SegmentationDerivation = derivations.Segmentation;
15
22
  const LABELMAP_SEG_SOP_CLASS_UID = '1.2.840.10008.5.1.4.1.1.66.7';
16
23
  const BITMAP_SEG_SOP_CLASS_UID = '1.2.840.10008.5.1.4.1.1.66.4';
24
+ const IMAGE_POSITION_PATIENT_TAG = 0x00200032;
25
+ const PLANE_POSITION_SEQUENCE_TAG = 0x00209113;
26
+ const STACK_ID_TAG = 0x00209056;
27
+ const IN_STACK_POSITION_NUMBER_TAG = 0x00209057;
28
+ const FRAME_CONTENT_SEQUENCE_TAG = 0x00209111;
17
29
  function resolveTransferSyntaxUid() {
18
30
  let options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
19
31
  const transferSyntaxUid = options.transferSyntaxUid || options.transferSyntaxUID;
@@ -84,8 +96,9 @@ function maxSegmentValue(labelmap3DArray, frameIndices) {
84
96
  return;
85
97
  }
86
98
  for (let i = 0; i < pixelData.length; i++) {
87
- if (pixelData[i] > max) {
88
- max = pixelData[i];
99
+ const segmentIndex = pixelData[i] ? getSegmentIndexForLabel(labelmap3D, pixelData[i]) : 0;
100
+ if (segmentIndex > max) {
101
+ max = segmentIndex;
89
102
  }
90
103
  }
91
104
  });
@@ -113,35 +126,157 @@ function collectSegmentSequence(labelmap3DArray) {
113
126
  return segment;
114
127
  });
115
128
  }
116
- function getPlaneSequencesForImage(image, metadata) {
117
- var _metadata$get;
118
- const imagePlane = metadata === null || metadata === void 0 || (_metadata$get = metadata.get) === null || _metadata$get === void 0 ? void 0 : _metadata$get.call(metadata, MetadataModules.IMAGE_PLANE, image === null || image === void 0 ? void 0 : image.imageId);
119
- if (!imagePlane) {
120
- return {};
121
- }
122
- const result = {};
123
- const imagePositionPatient = imagePlane.imagePositionPatient,
124
- imageOrientationPatient = imagePlane.imageOrientationPatient,
125
- rowCosines = imagePlane.rowCosines,
126
- columnCosines = imagePlane.columnCosines;
127
- if (Array.isArray(imagePositionPatient) && imagePositionPatient.length === 3) {
128
- result.planePositionSequence = {
129
- ImagePositionPatient: [...imagePositionPatient]
130
- };
129
+ function getOrientationIndex(orientations, orientation) {
130
+ let add = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
131
+ const index = orientations.findIndex(other => isEqual(other, orientation, GEOMETRY_TOLERANCE));
132
+ return index === -1 && add ? orientations.push(orientation) - 1 : index;
133
+ }
134
+ const POSITION_DIMENSION = {
135
+ DimensionIndexPointer: IMAGE_POSITION_PATIENT_TAG,
136
+ FunctionalGroupPointer: PLANE_POSITION_SEQUENCE_TAG,
137
+ DimensionDescriptionLabel: 'ImagePositionPatient'
138
+ };
139
+ const STACK_ID_DIMENSION = {
140
+ DimensionIndexPointer: STACK_ID_TAG,
141
+ FunctionalGroupPointer: FRAME_CONTENT_SEQUENCE_TAG,
142
+ DimensionDescriptionLabel: 'StackID'
143
+ };
144
+ const IN_STACK_POSITION_DIMENSION = {
145
+ DimensionIndexPointer: IN_STACK_POSITION_NUMBER_TAG,
146
+ FunctionalGroupPointer: FRAME_CONTENT_SEQUENCE_TAG,
147
+ DimensionDescriptionLabel: 'InStackPositionNumber'
148
+ };
149
+ function getLabelmapDimensions(frames) {
150
+ const missing = frames.findIndex(_ref3 => {
151
+ let position = _ref3.position,
152
+ orientation = _ref3.orientation;
153
+ return !position || !orientation;
154
+ });
155
+ if (missing !== -1) {
156
+ throw new Error("Cannot write a LABELMAP SEG: the source image of frame ".concat(missing + 1, " ") + "has no ImagePositionPatient or ImageOrientationPatient.");
131
157
  }
132
- let orientation = imageOrientationPatient;
133
- if ((!Array.isArray(orientation) || orientation.length !== 6) && Array.isArray(rowCosines) && Array.isArray(columnCosines)) {
134
- orientation = [...rowCosines, ...columnCosines];
158
+ const orientations = [];
159
+ const frameOrientations = frames.map(_ref4 => {
160
+ let orientation = _ref4.orientation;
161
+ return getOrientationIndex(orientations, orientation);
162
+ });
163
+ const normals = orientations.map(sliceNormal);
164
+ const distances = frames.map((_ref5, index) => {
165
+ let position = _ref5.position;
166
+ return vec3.dot(normals[frameOrientations[index]], position);
167
+ });
168
+ const planes = [];
169
+ let planeStart = 0;
170
+ frames.map((_, index) => index).sort((a, b) => frameOrientations[a] - frameOrientations[b] || distances[a] - distances[b]).forEach((index, i, sorted) => {
171
+ var _planes$previous;
172
+ const previous = sorted[i - 1];
173
+ const samePlane = i > 0 && frameOrientations[index] === frameOrientations[previous] && distances[index] - planeStart <= GEOMETRY_TOLERANCE;
174
+ if (!samePlane) {
175
+ planeStart = distances[index];
176
+ }
177
+ planes[index] = samePlane ? planes[previous] : ((_planes$previous = planes[previous]) !== null && _planes$previous !== void 0 ? _planes$previous : -1) + 1;
178
+ });
179
+ const planeCounts = [];
180
+ const orientationStacks = orientations.map(() => []);
181
+ const stacks = [];
182
+ frames.forEach((_, index) => {
183
+ var _planeCounts$planes$i, _stackIndexes$repeat;
184
+ const repeat = (_planeCounts$planes$i = planeCounts[planes[index]]) !== null && _planeCounts$planes$i !== void 0 ? _planeCounts$planes$i : 0;
185
+ planeCounts[planes[index]] = repeat + 1;
186
+ const stackIndexes = orientationStacks[frameOrientations[index]];
187
+ (_stackIndexes$repeat = stackIndexes[repeat]) !== null && _stackIndexes$repeat !== void 0 ? _stackIndexes$repeat : stackIndexes[repeat] = stacks.push([]) - 1;
188
+ stacks[stackIndexes[repeat]].push(index);
189
+ });
190
+ const frameContents = [];
191
+ stacks.forEach((stack, stackIndex) => {
192
+ [...stack].sort((a, b) => planes[a] - planes[b]).forEach((frameIndex, rank) => {
193
+ frameContents[frameIndex] = stacks.length === 1 ? {
194
+ DimensionIndexValues: [rank + 1]
195
+ } : {
196
+ StackID: String(stackIndex + 1),
197
+ InStackPositionNumber: rank + 1,
198
+ DimensionIndexValues: [stackIndex + 1, rank + 1]
199
+ };
200
+ });
201
+ });
202
+ return {
203
+ dimensions: stacks.length === 1 ? [POSITION_DIMENSION] : [STACK_ID_DIMENSION, IN_STACK_POSITION_DIMENSION],
204
+ frameContents,
205
+ orientations,
206
+ normals,
207
+ frameOrientations
208
+ };
209
+ }
210
+ function getSourceSliceSpacings(sourceImages, metadata, orientations, normals) {
211
+ const distances = orientations.map(() => []);
212
+ sourceImages.forEach(image => {
213
+ const _getSourceFrame = getSourceFrame(image, metadata),
214
+ position = _getSourceFrame.position,
215
+ orientation = _getSourceFrame.orientation;
216
+ const index = position && orientation ? getOrientationIndex(orientations, orientation, false) : -1;
217
+ if (index !== -1) {
218
+ distances[index].push(vec3.dot(normals[index], position));
219
+ }
220
+ });
221
+ return distances.map(planes => {
222
+ planes.sort((a, b) => a - b);
223
+ const gaps = planes.slice(1).map((distance, index) => distance - planes[index]).filter(gap => gap > GEOMETRY_TOLERANCE);
224
+ if (!gaps.length) {
225
+ return undefined;
226
+ }
227
+ const mean = gaps.reduce((sum, gap) => sum + gap, 0) / gaps.length;
228
+ return gaps.every(gap => Math.abs(gap - mean) <= mean * 0.01) ? mean : undefined;
229
+ });
230
+ }
231
+ const PIXEL_MEASURE_KEYS = ['PixelSpacing', 'SliceThickness', 'SpacingBetweenSlices'];
232
+ const isSameMeasure = (a, b) => a === b || isEqual(a, b, GEOMETRY_TOLERANCE);
233
+ function applyLabelmapPixelMeasures(dataset, frames, frameOrientations, sliceSpacings, includeSliceSpacing) {
234
+ var _toArray$;
235
+ const shared = dataset.SharedFunctionalGroupsSequence;
236
+ const _ref6 = (_toArray$ = toArray(shared.PixelMeasuresSequence)[0]) !== null && _toArray$ !== void 0 ? _toArray$ : {};
237
+ _ref6.SliceThickness;
238
+ _ref6.SpacingBetweenSlices;
239
+ const derived = _objectWithoutProperties(_ref6, _excluded);
240
+ const derivedPixelSpacing = toFiniteVector(derived.PixelSpacing, 2);
241
+ let spacingMissing = false;
242
+ const pixelMeasures = frames.map((frame, index) => {
243
+ var _frame$pixelSpacing, _frame$sliceThickness;
244
+ const sliceSpacing = sliceSpacings[frameOrientations[index]];
245
+ const measures = _objectSpread({}, derived);
246
+ const pixelSpacing = (_frame$pixelSpacing = frame.pixelSpacing) !== null && _frame$pixelSpacing !== void 0 ? _frame$pixelSpacing : derivedPixelSpacing;
247
+ if (pixelSpacing) {
248
+ measures.PixelSpacing = pixelSpacing;
249
+ }
250
+ const sliceThickness = (_frame$sliceThickness = frame.sliceThickness) !== null && _frame$sliceThickness !== void 0 ? _frame$sliceThickness : sliceSpacing;
251
+ if (sliceThickness !== undefined) {
252
+ measures.SliceThickness = sliceThickness;
253
+ }
254
+ if (includeSliceSpacing) {
255
+ if (sliceSpacing === undefined) {
256
+ spacingMissing = true;
257
+ } else {
258
+ measures.SpacingBetweenSlices = sliceSpacing;
259
+ }
260
+ }
261
+ return measures;
262
+ });
263
+ if (spacingMissing) {
264
+ cs3dLogger.warn('generateSegmentation: includeSliceSpacing is set, but the source ' + 'slices are not evenly spaced, there is only one slice, or not all ' + 'source images are loaded; the LABELMAP SEG omits Spacing Between ' + 'Slices.');
135
265
  }
136
- if (Array.isArray(orientation) && orientation.length === 6) {
137
- result.planeOrientationSequence = {
138
- ImageOrientationPatient: [...orientation]
139
- };
266
+ const _pixelMeasures = _slicedToArray(pixelMeasures, 1),
267
+ first = _pixelMeasures[0];
268
+ const same = pixelMeasures.every(measures => PIXEL_MEASURE_KEYS.every(key => isSameMeasure(measures[key], first[key])));
269
+ if (same) {
270
+ shared.PixelMeasuresSequence = first;
271
+ return undefined;
140
272
  }
141
- return result;
273
+ delete shared.PixelMeasuresSequence;
274
+ return pixelMeasures;
142
275
  }
143
276
  function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, images) {
277
+ var _toArray$0$DimensionO, _toArray$2;
144
278
  let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
279
+ let sourceImages = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : images;
145
280
  const labelmap3DArray = toLabelmap3DArray(inputLabelmaps3D);
146
281
  const segmentSequence = collectSegmentSequence(labelmap3DArray);
147
282
  const validFrameIndices = collectNonEmptyFrameIndices(labelmap3DArray);
@@ -171,10 +306,10 @@ function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, imag
171
306
  }
172
307
  const len = Math.min(source.length, frameLength);
173
308
  for (let i = 0; i < len; i++) {
174
- const value = source[i];
175
- if (value === 0) {
309
+ if (source[i] === 0) {
176
310
  continue;
177
311
  }
312
+ const value = getSegmentIndexForLabel(labelmap3D, source[i]);
178
313
  if (frame[i] !== 0 && frame[i] !== value && !overlapWarned) {
179
314
  cs3dLogger.warn('generateSegmentation: overlapping labelmap segments detected on the ' + 'same voxel while exporting a LABELMAP SEG; the later labelmap wins.');
180
315
  overlapWarned = true;
@@ -184,6 +319,21 @@ function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, imag
184
319
  });
185
320
  return frame;
186
321
  };
322
+ const frames = images.map((image, outputIndex) => {
323
+ const sourceImageSequenceItem = getReferencedSourceImageSequenceItem(image, metadata);
324
+ if (!(sourceImageSequenceItem !== null && sourceImageSequenceItem !== void 0 && sourceImageSequenceItem.ReferencedSOPInstanceUID)) {
325
+ throw new Error("Cannot resolve a source ReferencedSOPInstanceUID for labelmap SEG " + "frame ".concat(outputIndex + 1, ". Refusing to write a SEG with unreliable ") + "source image references.");
326
+ }
327
+ return _objectSpread(_objectSpread({}, getSourceFrame(image, metadata, true)), {}, {
328
+ sourceImageSequenceItem
329
+ });
330
+ });
331
+ const _getLabelmapDimension = getLabelmapDimensions(frames),
332
+ dimensions = _getLabelmapDimension.dimensions,
333
+ frameContents = _getLabelmapDimension.frameContents,
334
+ orientations = _getLabelmapDimension.orientations,
335
+ normals = _getLabelmapDimension.normals,
336
+ frameOrientations = _getLabelmapDimension.frameOrientations;
187
337
  const dataset = segmentation.dataset;
188
338
  dataset.NumberOfFrames = numberOfFrames;
189
339
  dataset.Rows = rows;
@@ -217,30 +367,46 @@ function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, imag
217
367
  Value: [LABELMAP_SEG_SOP_CLASS_UID],
218
368
  vr: 'UI'
219
369
  };
220
- const sourceImageSequence = images.map(image => getReferencedSourceImageSequenceItem(image, metadata)).filter(item => item.ReferencedSOPInstanceUID);
221
- if (sourceImageSequence.length) {
222
- dataset.SourceImageSequence = sourceImageSequence;
223
- }
224
- const perFrameInputs = validFrameIndices.map((_, outputIndex) => {
225
- var _dataset$PerFrameFunc, _dataset$PerFrameFunc2, _planeSequences$plane, _planeSequences$plane2;
226
- const image = images[outputIndex];
227
- const sourceImageSequenceItem = getReferencedSourceImageSequenceItem(image, metadata);
228
- if (!(sourceImageSequenceItem !== null && sourceImageSequenceItem !== void 0 && sourceImageSequenceItem.ReferencedSOPInstanceUID)) {
229
- throw new Error("Cannot resolve a source ReferencedSOPInstanceUID for labelmap SEG " + "frame ".concat(outputIndex, ". Refusing to write a SEG with unreliable ") + "source image references.");
230
- }
231
- const priorGroup = (_dataset$PerFrameFunc = (_dataset$PerFrameFunc2 = dataset.PerFrameFunctionalGroupsSequence) === null || _dataset$PerFrameFunc2 === void 0 ? void 0 : _dataset$PerFrameFunc2[outputIndex]) !== null && _dataset$PerFrameFunc !== void 0 ? _dataset$PerFrameFunc : {};
232
- const planeSequences = getPlaneSequencesForImage(image, metadata);
370
+ dataset.SourceImageSequence = frames.map(_ref7 => {
371
+ let sourceImageSequenceItem = _ref7.sourceImageSequenceItem;
372
+ return sourceImageSequenceItem;
373
+ });
374
+ const dimensionOrganizationUID = (_toArray$0$DimensionO = (_toArray$2 = toArray(dataset.DimensionOrganizationSequence)[0]) === null || _toArray$2 === void 0 ? void 0 : _toArray$2.DimensionOrganizationUID) !== null && _toArray$0$DimensionO !== void 0 ? _toArray$0$DimensionO : data.DicomMetaDictionary.uid();
375
+ dataset.DimensionOrganizationSequence = {
376
+ DimensionOrganizationUID: dimensionOrganizationUID
377
+ };
378
+ dataset.DimensionIndexSequence = dimensions.map(dimension => _objectSpread({
379
+ DimensionOrganizationUID: dimensionOrganizationUID
380
+ }, dimension));
381
+ normalizeSharedFunctionalGroupsSequence(dataset);
382
+ delete dataset.SharedFunctionalGroupsSequence.PlanePositionSequence;
383
+ const includeSliceSpacing = Boolean(options.includeSliceSpacing);
384
+ const sliceSpacings = includeSliceSpacing || frames.some(_ref8 => {
385
+ let sliceThickness = _ref8.sliceThickness;
386
+ return sliceThickness === undefined;
387
+ }) ? getSourceSliceSpacings(sourceImages, metadata, orientations, normals) : [];
388
+ const perFramePixelMeasures = applyLabelmapPixelMeasures(dataset, frames, frameOrientations, sliceSpacings, includeSliceSpacing);
389
+ dataset.PerFrameFunctionalGroupsSequence = [];
390
+ applyPerFrameFunctionalGroups(dataset, frames.map((_ref9, index) => {
391
+ let position = _ref9.position,
392
+ sourceImageSequenceItem = _ref9.sourceImageSequenceItem;
233
393
  return {
234
394
  sourceImageSequenceItem,
235
- planeOrientationSequence: (_planeSequences$plane = planeSequences.planeOrientationSequence) !== null && _planeSequences$plane !== void 0 ? _planeSequences$plane : priorGroup === null || priorGroup === void 0 ? void 0 : priorGroup.PlaneOrientationSequence,
236
- planePositionSequence: (_planeSequences$plane2 = planeSequences.planePositionSequence) !== null && _planeSequences$plane2 !== void 0 ? _planeSequences$plane2 : priorGroup === null || priorGroup === void 0 ? void 0 : priorGroup.PlanePositionSequence
395
+ planePositionSequence: {
396
+ ImagePositionPatient: position
397
+ },
398
+ pixelMeasuresSequence: perFramePixelMeasures === null || perFramePixelMeasures === void 0 ? void 0 : perFramePixelMeasures[index],
399
+ frameContent: frameContents[index]
237
400
  };
238
- });
239
- applyPerFrameFunctionalGroups(dataset, perFrameInputs);
240
- const sopInstanceUIDs = new Set(images.map(image => {
241
- var _metadata$get2;
242
- return (_metadata$get2 = metadata.get(MetadataModules.IMAGE_DATA, image === null || image === void 0 ? void 0 : image.imageId)) === null || _metadata$get2 === void 0 ? void 0 : _metadata$get2.SOPInstanceUID;
243
- }).filter(Boolean));
401
+ }));
402
+ setPlaneOrientations(dataset, frames.map(_ref0 => {
403
+ let orientation = _ref0.orientation;
404
+ return orientation;
405
+ }));
406
+ const sopInstanceUIDs = new Set(frames.map(_ref1 => {
407
+ let sourceImageSequenceItem = _ref1.sourceImageSequenceItem;
408
+ return sourceImageSequenceItem.ReferencedSOPInstanceUID;
409
+ }));
244
410
  const referencedSeriesSequence = dataset.ReferencedSeriesSequence;
245
411
  const referencedSeries = Array.isArray(referencedSeriesSequence) ? referencedSeriesSequence[0] : referencedSeriesSequence;
246
412
  if (referencedSeries !== null && referencedSeries !== void 0 && referencedSeries.ReferencedInstanceSequence && sopInstanceUIDs.size) {
@@ -289,7 +455,7 @@ function generateSegmentation(images, labelmaps, metadata) {
289
455
  const nonEmptyFrameIndices = collectNonEmptyFrameIndices(toLabelmap3DArray(labelmaps));
290
456
  const filteredImages = resolveReferencedImagesForExport(images, nonEmptyFrameIndices);
291
457
  const segmentation = _createMultiframeSegmentationFromReferencedImages(filteredImages, metadata, options);
292
- const segmentationResult = fillLabelmapSegmentation(segmentation, labelmaps, metadata, filteredImages, options);
458
+ const segmentationResult = fillLabelmapSegmentation(segmentation, labelmaps, metadata, filteredImages, options, images.every(image => image === null || image === void 0 ? void 0 : image.imageId) ? images : []);
293
459
  const predecessorImageId = options === null || options === void 0 ? void 0 : options.predecessorImageId;
294
460
  if (predecessorImageId) {
295
461
  const predecessor = metadata.get(MetadataModules.PREDECESSOR_SEQUENCE, predecessorImageId);
@@ -309,6 +475,7 @@ function _createMultiframeSegmentationFromReferencedImages(images, metadata, opt
309
475
  const seriesData = metadata.get(MetadataModules.SERIES_DATA, imageId);
310
476
  const imageData = metadata.get(MetadataModules.IMAGE_DATA, imageId);
311
477
  return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, studyData), seriesData), imageData), {}, {
478
+ NumberOfFrames: 1,
312
479
  PixelData: image.voxelManager.getScalarData(),
313
480
  BitsAllocated: 16,
314
481
  _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 = [];
@@ -14,4 +14,11 @@ export function applyPerFrameFunctionalGroups(dataset: object, frames: Array<{
14
14
  };
15
15
  planeOrientationSequence?: object;
16
16
  planePositionSequence?: object;
17
+ frameContent?: {
18
+ DimensionIndexValues: number[];
19
+ StackID?: string;
20
+ InStackPositionNumber?: number;
21
+ };
22
+ pixelMeasuresSequence?: object;
17
23
  }>): void;
24
+ export function setPlaneOrientations(dataset: object, frameOrientations: Array<number[] | undefined>): void;
@@ -1,6 +1,9 @@
1
+ import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
1
2
  import _defineProperty from '@babel/runtime/helpers/defineProperty';
2
3
  import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
3
- import { Enums, utilities } from '@cornerstonejs/core';
4
+ import { Enums, utilities as utilities$1 } from '@cornerstonejs/core';
5
+ import { utilities } from '@cornerstonejs/metadata';
6
+ import { GEOMETRY_TOLERANCE } from './sourceFrame.js';
4
7
 
5
8
  const _excluded = ["SegmentIdentificationSequence"];
6
9
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
@@ -27,7 +30,7 @@ function getReferencedFrameNumber(imageId, metadata) {
27
30
  return undefined;
28
31
  }
29
32
  const providerFrame = metadata === null || metadata === void 0 || (_metadata$getFrameInf = metadata.getFrameInformationFromURL) === null || _metadata$getFrameInf === void 0 ? void 0 : _metadata$getFrameInf.call(metadata, imageId);
30
- const frameNumber = providerFrame != null ? Number(providerFrame) : utilities.FrameRange.imageIdToFrameStart(imageId);
33
+ const frameNumber = providerFrame != null ? Number(providerFrame) : utilities$1.FrameRange.imageIdToFrameStart(imageId);
31
34
  return Number.isFinite(frameNumber) ? frameNumber : undefined;
32
35
  }
33
36
 
@@ -68,6 +71,8 @@ function normalizeSharedFunctionalGroupsSequence(dataset) {
68
71
  * sourceImageSequenceItem: { ReferencedSOPInstanceUID: string, ReferencedFrameNumber?: number },
69
72
  * planeOrientationSequence?: object,
70
73
  * planePositionSequence?: object,
74
+ * frameContent?: { DimensionIndexValues: number[], StackID?: string, InStackPositionNumber?: number },
75
+ * pixelMeasuresSequence?: object,
71
76
  * }>} frames
72
77
  *
73
78
  * `referencedSegmentNumber` drives the per-frame `SegmentIdentificationSequence`
@@ -75,6 +80,10 @@ function normalizeSharedFunctionalGroupsSequence(dataset) {
75
80
  * single frame carries many segment labels as pixel values, so the standard
76
81
  * forbids the macro and a fixed `ReferencedSegmentNumber` would be wrong for any
77
82
  * label other than the one hard-coded.
83
+ *
84
+ * `frameContent` replaces the frame's `FrameContentSequence`. Callers that
85
+ * build the per-frame groups from scratch (LABELMAP SEGs) must pass it, since
86
+ * the Frame Content macro is mandatory for every Segmentation frame.
78
87
  */
79
88
  function applyPerFrameFunctionalGroups(dataset, frames) {
80
89
  normalizeSharedFunctionalGroupsSequence(dataset);
@@ -107,10 +116,62 @@ function applyPerFrameFunctionalGroups(dataset, frames) {
107
116
  if (frame.planePositionSequence) {
108
117
  group.PlanePositionSequence = frame.planePositionSequence;
109
118
  }
119
+ if (frame.pixelMeasuresSequence) {
120
+ group.PixelMeasuresSequence = frame.pixelMeasuresSequence;
121
+ }
122
+ if (frame.frameContent) {
123
+ group.FrameContentSequence = frame.frameContent;
124
+ }
110
125
  return group;
111
126
  });
112
127
  dataset.PerFrameFunctionalGroupsSequence = nextSequence;
113
128
  dataset.NumberOfFrames = nextSequence.length;
114
129
  }
115
130
 
116
- export { applyPerFrameFunctionalGroups, getReferencedFrameNumber, getReferencedSourceImageSequenceItem, normalizeSharedFunctionalGroupsSequence };
131
+ /**
132
+ * Writes the PlaneOrientationSequence of each frame in the shared group or in
133
+ * the per-frame groups, never in both (PS3.3 C.7.6.16). When all frames have
134
+ * one orientation, within GEOMETRY_TOLERANCE, it goes in the shared group
135
+ * only. Otherwise each frame gets its own orientation in its per-frame group,
136
+ * and a frame without one keeps its current per-frame orientation, or else the
137
+ * current shared orientation. When no frame has a known orientation, the
138
+ * dataset does not change.
139
+ *
140
+ * Call it after the per-frame groups are built.
141
+ *
142
+ * @param {object} dataset - SEG dataset
143
+ * @param {Array<number[]|undefined>} frameOrientations - the
144
+ * ImageOrientationPatient of each frame, or undefined when it is not known
145
+ */
146
+ function setPlaneOrientations(dataset, frameOrientations) {
147
+ var _dataset$PerFrameFunc;
148
+ normalizeSharedFunctionalGroupsSequence(dataset);
149
+ const shared = dataset.SharedFunctionalGroupsSequence;
150
+ const perFrame = (_dataset$PerFrameFunc = dataset.PerFrameFunctionalGroupsSequence) !== null && _dataset$PerFrameFunc !== void 0 ? _dataset$PerFrameFunc : [];
151
+ const _frameOrientations = _slicedToArray(frameOrientations, 1),
152
+ first = _frameOrientations[0];
153
+ if (!frameOrientations.some(Boolean)) {
154
+ return;
155
+ }
156
+ if (first && frameOrientations.every(orientation => utilities.isEqual(orientation, first, GEOMETRY_TOLERANCE))) {
157
+ shared.PlaneOrientationSequence = {
158
+ ImageOrientationPatient: first
159
+ };
160
+ perFrame.forEach(group => delete group.PlaneOrientationSequence);
161
+ return;
162
+ }
163
+ const sharedOrientation = shared.PlaneOrientationSequence;
164
+ delete shared.PlaneOrientationSequence;
165
+ perFrame.forEach((group, index) => {
166
+ const orientation = frameOrientations[index];
167
+ if (orientation) {
168
+ group.PlaneOrientationSequence = {
169
+ ImageOrientationPatient: orientation
170
+ };
171
+ } else if (!group.PlaneOrientationSequence && sharedOrientation) {
172
+ group.PlaneOrientationSequence = sharedOrientation;
173
+ }
174
+ });
175
+ }
176
+
177
+ export { applyPerFrameFunctionalGroups, getReferencedFrameNumber, getReferencedSourceImageSequenceItem, normalizeSharedFunctionalGroupsSequence, setPlaneOrientations };
@@ -0,0 +1,14 @@
1
+ declare const GEOMETRY_TOLERANCE = 0.001;
2
+ declare function toFiniteVector(values: any, length: number): number[] | undefined;
3
+ interface SourceFrame {
4
+ position?: number[];
5
+ orientation?: number[];
6
+ sliceThickness?: number;
7
+ pixelSpacing?: number[];
8
+ }
9
+ declare function getSourceFrame(image: {
10
+ imageId?: string;
11
+ } | undefined, metadata: any, withPixelMeasures?: boolean): SourceFrame;
12
+ declare const sliceNormal: (orientation: number[]) => number[];
13
+ export { GEOMETRY_TOLERANCE, getSourceFrame, sliceNormal, toFiniteVector };
14
+ export type { SourceFrame };
@@ -0,0 +1,60 @@
1
+ import { Enums } from '@cornerstonejs/core';
2
+ import { utilities } from '@cornerstonejs/metadata';
3
+ import { vec3 } from 'gl-matrix';
4
+
5
+ const isEqual = utilities.isEqual,
6
+ toFiniteNumber = utilities.toFiniteNumber;
7
+ const MetadataModules = Enums.MetadataModules;
8
+ const GEOMETRY_TOLERANCE = 1e-3;
9
+ const DEFAULT_POSITION = [0, 0, 0];
10
+ const DEFAULT_ORIENTATION = [1, 0, 0, 0, 1, 0];
11
+ const DEFAULT_PIXEL_SPACING = [1, 1];
12
+ function toFiniteVector(values, length) {
13
+ const numbers = toFiniteNumber(values);
14
+ return Array.isArray(numbers) && numbers.length === length && numbers.every(Number.isFinite) ? numbers : undefined;
15
+ }
16
+ function getSourceFrame(image, metadata) {
17
+ var _metadata$get, _metadata$get2, _toOrientation, _metadata$get3, _metadata$get4, _toFiniteVector;
18
+ let withPixelMeasures = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
19
+ const imageId = image === null || image === void 0 ? void 0 : image.imageId;
20
+ const plane = (_metadata$get = metadata === null || metadata === void 0 || (_metadata$get2 = metadata.get) === null || _metadata$get2 === void 0 ? void 0 : _metadata$get2.call(metadata, MetadataModules.IMAGE_PLANE, imageId)) !== null && _metadata$get !== void 0 ? _metadata$get : {};
21
+ const rowCosines = plane.rowCosines,
22
+ columnCosines = plane.columnCosines,
23
+ usingDefaultValues = plane.usingDefaultValues;
24
+ const notDefault = (value, defaultValue) => usingDefaultValues && isEqual(value, defaultValue) ? undefined : value;
25
+ const cosineFlags = [plane.isDefaultValueSetForRowCosine, plane.isDefaultValueSetForColumnCosine];
26
+ const planeOrientation = (_toOrientation = toOrientation(plane.imageOrientationPatient)) !== null && _toOrientation !== void 0 ? _toOrientation : rowCosines && columnCosines ? toOrientation([...rowCosines, ...columnCosines]) : undefined;
27
+ let position = notDefault(toFiniteVector(plane.imagePositionPatient, 3), DEFAULT_POSITION);
28
+ let orientation = cosineFlags.some(flag => flag !== undefined) ? cosineFlags.some(Boolean) ? undefined : planeOrientation : notDefault(planeOrientation, DEFAULT_ORIENTATION);
29
+ if (position && orientation && !withPixelMeasures) {
30
+ return {
31
+ position,
32
+ orientation
33
+ };
34
+ }
35
+ const instance = (_metadata$get3 = metadata === null || metadata === void 0 || (_metadata$get4 = metadata.get) === null || _metadata$get4 === void 0 ? void 0 : _metadata$get4.call(metadata, MetadataModules.IMAGE_DATA, imageId)) !== null && _metadata$get3 !== void 0 ? _metadata$get3 : {};
36
+ position !== null && position !== void 0 ? position : position = toFiniteVector(instance.ImagePositionPatient, 3);
37
+ orientation !== null && orientation !== void 0 ? orientation : orientation = toOrientation(instance.ImageOrientationPatient);
38
+ if (!withPixelMeasures) {
39
+ return {
40
+ position,
41
+ orientation
42
+ };
43
+ }
44
+ return {
45
+ position,
46
+ orientation,
47
+ sliceThickness: [plane.sliceThickness, instance.SliceThickness].map(Number).find(thickness => thickness > 0),
48
+ pixelSpacing: (_toFiniteVector = toFiniteVector(instance.PixelSpacing, 2)) !== null && _toFiniteVector !== void 0 ? _toFiniteVector : notDefault(toFiniteVector(plane.pixelSpacing, 2), DEFAULT_PIXEL_SPACING)
49
+ };
50
+ }
51
+ const sliceNormal = orientation => {
52
+ const normal = vec3.cross([0, 0, 0], orientation.slice(0, 3), orientation.slice(3, 6));
53
+ return vec3.normalize(normal, normal);
54
+ };
55
+ function toOrientation(values) {
56
+ const orientation = toFiniteVector(values, 6);
57
+ return orientation && vec3.length(sliceNormal(orientation)) > GEOMETRY_TOLERANCE ? orientation : undefined;
58
+ }
59
+
60
+ export { GEOMETRY_TOLERANCE, getSourceFrame, sliceNormal, toFiniteVector };
@@ -1 +1 @@
1
- export declare const version = "5.11.7";
1
+ export declare const version = "5.12.1";
@@ -1,3 +1,3 @@
1
- const version = '5.11.7';
1
+ const version = '5.12.1';
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.7",
3
+ "version": "5.12.1",
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.7",
103
- "@cornerstonejs/metadata": "5.11.7",
104
- "@cornerstonejs/tools": "5.11.7"
102
+ "@cornerstonejs/core": "5.12.1",
103
+ "@cornerstonejs/metadata": "5.12.1",
104
+ "@cornerstonejs/tools": "5.12.1"
105
105
  },
106
106
  "peerDependencies": {
107
- "@cornerstonejs/core": "5.11.7",
108
- "@cornerstonejs/metadata": "5.11.7",
109
- "@cornerstonejs/tools": "5.11.7"
107
+ "@cornerstonejs/core": "5.12.1",
108
+ "@cornerstonejs/metadata": "5.12.1",
109
+ "@cornerstonejs/tools": "5.12.1"
110
110
  }
111
111
  }