@ohif/app 3.14.0-beta.54 → 3.14.0-beta.56

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.
Files changed (37) hide show
  1. package/dist/{9187.bundle.47a04a89.js → 1283.bundle.56abacf4.js} +162 -137
  2. package/dist/{4262.bundle.0c550b7f.js → 1558.bundle.03d5783b.js} +36 -11
  3. package/dist/{1566.bundle.8d90bb15.js → 1566.bundle.e9f5d851.js} +5 -1
  4. package/dist/{1645.bundle.65cff869.js → 1645.bundle.618a2886.js} +700 -389
  5. package/dist/{1724.bundle.b4757283.js → 1724.bundle.59b20c59.js} +1184 -1139
  6. package/dist/{1788.bundle.5b78672d.js → 1788.bundle.3f1349d2.js} +101 -43
  7. package/dist/1975.bundle.53cf5d7c.js +8216 -0
  8. package/dist/{5922.bundle.46b3e037.js → 2894.bundle.db3f8686.js} +240 -151
  9. package/dist/{6567.bundle.cc57e572.js → 3044.bundle.039294b9.js} +105 -76
  10. package/dist/{3386.bundle.b835901b.js → 3386.bundle.a9fd7dfd.js} +92 -23
  11. package/dist/{4004.bundle.da822fd2.js → 4018.bundle.48c288e5.js} +128 -253
  12. package/dist/{2894.bundle.d612efb2.js → 513.bundle.9c0548cf.js} +1 -1
  13. package/dist/{5143.bundle.62bcf4ee.js → 5143.bundle.67167d39.js} +219 -147
  14. package/dist/{5895.bundle.b4892e1b.js → 5320.bundle.0c7b2cb7.js} +1473 -617
  15. package/dist/{5383.bundle.d393d2f5.js → 5383.bundle.79243338.js} +26 -4
  16. package/dist/{4324.bundle.8645d6b4.js → 5888.bundle.cd717f42.js} +1364 -8004
  17. package/dist/{8128.bundle.2afe5a05.js → 5914.bundle.00f408d2.js} +419 -49
  18. package/dist/{1284.bundle.a489bd1d.js → 5989.bundle.f8096a4e.js} +1175 -616
  19. package/dist/{6255.bundle.ee378f1c.js → 6255.bundle.521051c1.js} +42 -18
  20. package/dist/{829.bundle.e60fee3a.js → 641.bundle.4627a8e1.js} +472 -483
  21. package/dist/{1568.bundle.474a5a93.js → 9187.bundle.237037e4.js} +1 -1
  22. package/dist/{6711.bundle.baba2ccd.js → 9232.bundle.3b0caf8e.js} +10 -10
  23. package/dist/{1895.bundle.923d0bd4.js → 9620.bundle.67375c83.js} +82 -24
  24. package/dist/{app.bundle.871d916b.js → app.bundle.5a277c45.js} +44 -44
  25. package/dist/{compute.bundle.caab94e6.js → compute.bundle.a8f26c49.js} +10 -10
  26. package/dist/index.html +1 -1
  27. package/dist/{interpolation.bundle.eed65b60.js → interpolation.bundle.aef2f614.js} +5 -5
  28. package/dist/{polySeg.bundle.34a58c4f.js → polySeg.bundle.ba052ac3.js} +11 -11
  29. package/dist/static/wasm/{27ff970b98.module.wasm → 0e14aeab30.module.wasm} +0 -0
  30. package/dist/static/wasm/58a146bc8c.module.wasm +0 -0
  31. package/dist/static/wasm/99a2672e64.module.wasm +0 -0
  32. package/dist/static/wasm/{11f8dc2413.module.wasm → d8b213f3ea.module.wasm} +0 -0
  33. package/dist/sw.js +1 -1
  34. package/package.json +6 -6
  35. package/dist/0.bundle.485115b4.js +0 -4498
  36. package/dist/static/wasm/58769f1d7d.module.wasm +0 -0
  37. /package/dist/{1895.bundle.css → 9620.bundle.css} +0 -0
@@ -1821,764 +1821,356 @@ function getDatasetsFromImages(images, isMultiframe, options) {
1821
1821
 
1822
1822
 
1823
1823
 
1824
- ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone/Segmentation_3X.js
1824
+ // EXTERNAL MODULE: ../../node_modules/gl-matrix/esm/index.js
1825
+ var gl_matrix_esm = __webpack_require__(50341);
1826
+ ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/helpers/checkIfPerpendicular.js
1827
+ function checkIfPerpendicular(iop1, iop2, tolerance) {
1828
+ const absDotColumnCosines = Math.abs(iop1[0] * iop2[0] + iop1[1] * iop2[1] + iop1[2] * iop2[2]);
1829
+ const absDotRowCosines = Math.abs(iop1[3] * iop2[3] + iop1[4] * iop2[4] + iop1[5] * iop2[5]);
1830
+ return (absDotColumnCosines < tolerance || Math.abs(absDotColumnCosines - 1) < tolerance) && (absDotRowCosines < tolerance || Math.abs(absDotRowCosines - 1) < tolerance);
1831
+ }
1825
1832
 
1826
1833
 
1827
1834
 
1835
+ ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/helpers/checkOrientation.js
1828
1836
 
1829
1837
 
1830
- const Segmentation_3X_cs3dLogger = esm.utilities.logger.adaptersLog.getLogger('Cornerstone.Segmentation_3X');
1831
- const _utilities$orientatio = dcmjs_es/* .utilities.orientation */.BF.orientation,
1832
- rotateDirectionCosinesInPlane = _utilities$orientatio.rotateDirectionCosinesInPlane,
1833
- flipIOP = _utilities$orientatio.flipImageOrientationPatient,
1834
- flipMatrix2D = _utilities$orientatio.flipMatrix2D,
1835
- rotateMatrix902D = _utilities$orientatio.rotateMatrix902D;
1836
- const Segmentation_3X_datasetToBlob = dcmjs_es/* .utilities.datasetToBlob */.BF.datasetToBlob,
1837
- BitArray = dcmjs_es/* .utilities.BitArray */.BF.BitArray,
1838
- Segmentation_3X_DicomMessage = dcmjs_es/* .utilities.DicomMessage */.BF.DicomMessage,
1839
- Segmentation_3X_DicomMetaDictionary = dcmjs_es/* .utilities.DicomMetaDictionary */.BF.DicomMetaDictionary;
1840
- const Segmentation_3X_Normalizer = dcmjs_es/* .normalizers.Normalizer */.z8.Normalizer;
1841
- const SegmentationDerivation = dcmjs_es/* .derivations.Segmentation */.h4.Segmentation;
1842
- const Segmentation = {
1843
- generateSegmentation,
1844
- generateToolState
1845
- };
1838
+
1839
+ function checkOrientation(multiframe, validOrientations, sourceDataDimensions, tolerance) {
1840
+ const SharedFunctionalGroupsSequence = multiframe.SharedFunctionalGroupsSequence,
1841
+ PerFrameFunctionalGroupsSequence = multiframe.PerFrameFunctionalGroupsSequence;
1842
+ const sharedImageOrientationPatient = SharedFunctionalGroupsSequence.PlaneOrientationSequence ? SharedFunctionalGroupsSequence.PlaneOrientationSequence.ImageOrientationPatient : undefined;
1843
+ const PerFrameFunctionalGroups = PerFrameFunctionalGroupsSequence[0];
1844
+ const iopRaw = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
1845
+ const iop = Array.isArray(iopRaw) ? iopRaw.map(Number) : iopRaw;
1846
+ const inPlane = validOrientations.some(operation => esm.utilities.isEqual(iop, operation, tolerance));
1847
+ if (inPlane) {
1848
+ return 'Planar';
1849
+ }
1850
+ if (checkIfPerpendicular(iop, validOrientations[0], tolerance) && sourceDataDimensions.includes(multiframe.Rows) && sourceDataDimensions.includes(multiframe.Columns)) {
1851
+ return 'Perpendicular';
1852
+ }
1853
+ return 'Oblique';
1854
+ }
1855
+
1856
+
1857
+
1858
+ // EXTERNAL MODULE: ../../node_modules/@cornerstonejs/metadata/dist/esm/index.js + 29 modules
1859
+ var dist_esm = __webpack_require__(76368);
1860
+ // EXTERNAL MODULE: ../../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
1861
+ var objectWithoutProperties = __webpack_require__(39850);
1862
+ ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/Segmentation/perFrameFunctionalGroups.js
1863
+
1864
+
1865
+
1866
+
1867
+ const _excluded = ["SegmentIdentificationSequence"];
1868
+ function perFrameFunctionalGroups_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; }
1869
+ function perFrameFunctionalGroups_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? perFrameFunctionalGroups_ownKeys(Object(t), !0).forEach(function (r) { (0,defineProperty/* ["default"] */.A)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : perFrameFunctionalGroups_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
1870
+ const MetadataModules = esm.Enums.MetadataModules;
1846
1871
 
1847
1872
  /**
1873
+ * Resolves the 1-based DICOM frame number referenced by an imageId.
1848
1874
  *
1849
- * @typedef {Object} BrushData
1850
- * @property {Object} toolState - The cornerstoneTools global toolState.
1851
- * @property {Object[]} segments - The cornerstoneTools segment metadata that corresponds to the
1852
- * seriesInstanceUid.
1875
+ * Prefer the metadata provider's own frame extraction when it offers one — it
1876
+ * understands the full set of imageId shapes the host app produces (wadors
1877
+ * `/frames/N` as well as `?frame=N` / `&frame=N`). Fall back to the core
1878
+ * FrameRange helper (handles `/frames/N` and `frameNumber=N`) so that
1879
+ * provider-agnostic callers still resolve multi-frame references. A one-off
1880
+ * `/[?&]frame=/` regex silently drops the wadors form, so it must not be used.
1881
+ *
1882
+ * @param {string} imageId
1883
+ * @param {object} metadata - metadata provider
1884
+ * @returns {number|undefined}
1853
1885
  */
1886
+ function getReferencedFrameNumber(imageId, metadata) {
1887
+ var _metadata$getFrameInf;
1888
+ if (!imageId) {
1889
+ return undefined;
1890
+ }
1891
+ const providerFrame = metadata === null || metadata === void 0 || (_metadata$getFrameInf = metadata.getFrameInformationFromURL) === null || _metadata$getFrameInf === void 0 ? void 0 : _metadata$getFrameInf.call(metadata, imageId);
1892
+ const frameNumber = providerFrame != null ? Number(providerFrame) : esm.utilities.FrameRange.imageIdToFrameStart(imageId);
1893
+ return Number.isFinite(frameNumber) ? frameNumber : undefined;
1894
+ }
1854
1895
 
1855
1896
  /**
1856
- * generateSegmentation - Generates cornerstoneTools brush data, given a stack of
1857
- * imageIds, images and the cornerstoneTools brushData.
1897
+ * Builds a SourceImageSequence item (ReferencedSOPInstanceUID + optional
1898
+ * ReferencedFrameNumber) for a cornerstone image, using the shared frame
1899
+ * extraction so all SEG export paths resolve multi-frame references identically.
1858
1900
  *
1859
- * @param {object[]} images An array of the cornerstone image objects.
1860
- * @param {BrushData} brushData and object containing the brushData.
1861
- * @returns {type} description
1901
+ * @param {{ imageId?: string }} image
1902
+ * @param {object} metadata - metadata provider
1903
+ * @returns {{ ReferencedSOPInstanceUID: string, ReferencedFrameNumber?: number }}
1862
1904
  */
1863
- function generateSegmentation(images, brushData) {
1864
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
1865
- includeSliceSpacing: true
1866
- };
1867
- const toolState = brushData.toolState,
1868
- segments = brushData.segments;
1869
-
1870
- // Calculate the dimensions of the data cube.
1871
- const image0 = images[0];
1872
- const dims = {
1873
- x: image0.columns,
1874
- y: image0.rows,
1875
- z: images.length
1905
+ function getReferencedSourceImageSequenceItem(image, metadata) {
1906
+ var _metadata$get;
1907
+ const imageData = (metadata === null || metadata === void 0 || (_metadata$get = metadata.get) === null || _metadata$get === void 0 ? void 0 : _metadata$get.call(metadata, MetadataModules.IMAGE_DATA, image === null || image === void 0 ? void 0 : image.imageId)) || {};
1908
+ const referencedFrameNumber = getReferencedFrameNumber(image === null || image === void 0 ? void 0 : image.imageId, metadata);
1909
+ const item = {
1910
+ ReferencedSOPInstanceUID: imageData.SOPInstanceUID
1876
1911
  };
1877
- dims.xy = dims.x * dims.y;
1878
- const numSegments = _getSegCount(seg, segments);
1879
- if (!numSegments) {
1880
- throw new Error('No segments to export!');
1912
+ if (Number.isFinite(referencedFrameNumber) && referencedFrameNumber > 0) {
1913
+ item.ReferencedFrameNumber = referencedFrameNumber;
1881
1914
  }
1882
- const isMultiframe = image0.imageId.includes('?frame');
1883
- const seg = _createSegFromImages(images, isMultiframe, options);
1884
- const _getNumberOfFramesPer = _getNumberOfFramesPerSegment(toolState, images, segments),
1885
- referencedFramesPerSegment = _getNumberOfFramesPer.referencedFramesPerSegment,
1886
- segmentIndicies = _getNumberOfFramesPer.segmentIndicies;
1887
- let NumberOfFrames = 0;
1888
- for (let i = 0; i < referencedFramesPerSegment.length; i++) {
1889
- NumberOfFrames += referencedFramesPerSegment[i].length;
1915
+ return item;
1916
+ }
1917
+ function normalizeSharedFunctionalGroupsSequence(dataset) {
1918
+ const shared = dataset.SharedFunctionalGroupsSequence;
1919
+ if (Array.isArray(shared) && shared.length > 0) {
1920
+ dataset.SharedFunctionalGroupsSequence = shared[0];
1921
+ } else if (!shared || typeof shared !== 'object') {
1922
+ dataset.SharedFunctionalGroupsSequence = {};
1890
1923
  }
1891
- seg.setNumberOfFrames(NumberOfFrames);
1892
- for (let i = 0; i < segmentIndicies.length; i++) {
1893
- const segmentIndex = segmentIndicies[i];
1894
- const referencedFrameIndicies = referencedFramesPerSegment[i];
1924
+ }
1895
1925
 
1896
- // Frame numbers start from 1.
1897
- const referencedFrameNumbers = referencedFrameIndicies.map(element => {
1898
- return element + 1;
1926
+ /**
1927
+ * @param {object} dataset - SEG dataset
1928
+ * @param {Array<{
1929
+ * referencedSegmentNumber?: number,
1930
+ * sourceImageSequenceItem: { ReferencedSOPInstanceUID: string, ReferencedFrameNumber?: number },
1931
+ * planeOrientationSequence?: object,
1932
+ * planePositionSequence?: object,
1933
+ * }>} frames
1934
+ *
1935
+ * `referencedSegmentNumber` drives the per-frame `SegmentIdentificationSequence`
1936
+ * macro (one segment per frame — BINARY SEGs). Omit it for LABELMAP SEGs: there a
1937
+ * single frame carries many segment labels as pixel values, so the standard
1938
+ * forbids the macro and a fixed `ReferencedSegmentNumber` would be wrong for any
1939
+ * label other than the one hard-coded.
1940
+ */
1941
+ function applyPerFrameFunctionalGroups(dataset, frames) {
1942
+ normalizeSharedFunctionalGroupsSequence(dataset);
1943
+ const validFrames = frames.filter(frame => {
1944
+ var _frame$sourceImageSeq;
1945
+ return frame === null || frame === void 0 || (_frame$sourceImageSeq = frame.sourceImageSequenceItem) === null || _frame$sourceImageSeq === void 0 ? void 0 : _frame$sourceImageSeq.ReferencedSOPInstanceUID;
1946
+ });
1947
+ const existing = dataset.PerFrameFunctionalGroupsSequence;
1948
+ const existingList = Array.isArray(existing) ? existing : [];
1949
+ const nextSequence = validFrames.map((frame, index) => {
1950
+ const prior = existingList[index] && typeof existingList[index] === 'object' ? existingList[index] : {};
1951
+
1952
+ // Drop any inherited SegmentIdentificationSequence when this frame has no
1953
+ // referencedSegmentNumber (LABELMAP path) so the macro is truly absent.
1954
+ prior.SegmentIdentificationSequence;
1955
+ const priorRest = (0,objectWithoutProperties/* ["default"] */.A)(prior, _excluded);
1956
+ const group = perFrameFunctionalGroups_objectSpread(perFrameFunctionalGroups_objectSpread({}, priorRest), {}, {
1957
+ DerivationImageSequence: [{
1958
+ SourceImageSequence: [frame.sourceImageSequenceItem]
1959
+ }]
1899
1960
  });
1900
- const segment = segments[segmentIndex];
1901
- seg.addSegment(segment, _extractCornerstoneToolsPixelData(segmentIndex, referencedFrameIndicies, toolState, images, dims), referencedFrameNumbers);
1902
- }
1903
- seg.bitPackPixelData();
1904
- const segBlob = Segmentation_3X_datasetToBlob(seg.dataset);
1905
- return segBlob;
1906
- }
1907
- function _extractCornerstoneToolsPixelData(segmentIndex, referencedFrames, toolState, images, dims) {
1908
- const pixelData = new Uint8Array(dims.xy * referencedFrames.length);
1909
- let pixelDataIndex = 0;
1910
- for (let i = 0; i < referencedFrames.length; i++) {
1911
- const frame = referencedFrames[i];
1912
- const imageId = images[frame].imageId;
1913
- const imageIdSpecificToolState = toolState[imageId];
1914
- const brushPixelData = imageIdSpecificToolState.brush.data[segmentIndex].pixelData;
1915
- for (let p = 0; p < brushPixelData.length; p++) {
1916
- pixelData[pixelDataIndex] = brushPixelData[p];
1917
- pixelDataIndex++;
1961
+ if (frame.referencedSegmentNumber != null) {
1962
+ group.SegmentIdentificationSequence = {
1963
+ ReferencedSegmentNumber: frame.referencedSegmentNumber
1964
+ };
1918
1965
  }
1919
- }
1920
- return pixelData;
1921
- }
1922
- function _getNumberOfFramesPerSegment(toolState, images, segments) {
1923
- const segmentIndicies = [];
1924
- const referencedFramesPerSegment = [];
1925
- for (let i = 0; i < segments.length; i++) {
1926
- if (segments[i]) {
1927
- segmentIndicies.push(i);
1928
- referencedFramesPerSegment.push([]);
1966
+ if (frame.planeOrientationSequence) {
1967
+ group.PlaneOrientationSequence = frame.planeOrientationSequence;
1929
1968
  }
1930
- }
1931
- for (let z = 0; z < images.length; z++) {
1932
- const imageId = images[z].imageId;
1933
- const imageIdSpecificToolState = toolState[imageId];
1934
- for (let i = 0; i < segmentIndicies.length; i++) {
1935
- const segIdx = segmentIndicies[i];
1936
- if (imageIdSpecificToolState && imageIdSpecificToolState.brush && imageIdSpecificToolState.brush.data && imageIdSpecificToolState.brush.data[segIdx] && imageIdSpecificToolState.brush.data[segIdx].pixelData) {
1937
- referencedFramesPerSegment[i].push(z);
1938
- }
1969
+ if (frame.planePositionSequence) {
1970
+ group.PlanePositionSequence = frame.planePositionSequence;
1939
1971
  }
1972
+ return group;
1973
+ });
1974
+ dataset.PerFrameFunctionalGroupsSequence = nextSequence;
1975
+ dataset.NumberOfFrames = nextSequence.length;
1976
+ }
1977
+
1978
+
1979
+
1980
+ ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/encodePixelData.js
1981
+
1982
+
1983
+ const RLE_LOSSLESS_TRANSFER_SYNTAX_UID = '1.2.840.10008.1.2.5';
1984
+ const EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID = dcmjs_es/* .constants.EXPLICIT_LITTLE_ENDIAN */.AA.EXPLICIT_LITTLE_ENDIAN;
1985
+ function getTransferSyntaxUid(multiframe) {
1986
+ var _meta$TransferSyntaxU;
1987
+ const meta = multiframe._meta;
1988
+ const fromMeta = meta === null || meta === void 0 || (_meta$TransferSyntaxU = meta.TransferSyntaxUID) === null || _meta$TransferSyntaxU === void 0 || (_meta$TransferSyntaxU = _meta$TransferSyntaxU.Value) === null || _meta$TransferSyntaxU === void 0 ? void 0 : _meta$TransferSyntaxU[0];
1989
+ if (fromMeta) {
1990
+ return fromMeta;
1940
1991
  }
1941
- return {
1942
- referencedFramesPerSegment,
1943
- segmentIndicies
1944
- };
1992
+ if (typeof multiframe.TransferSyntaxUID === 'string') {
1993
+ return multiframe.TransferSyntaxUID;
1994
+ }
1995
+ return EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID;
1945
1996
  }
1946
- function _getSegCount(seg, segments) {
1947
- let numSegments = 0;
1948
- for (let i = 0; i < segments.length; i++) {
1949
- if (segments[i]) {
1950
- numSegments++;
1951
- }
1997
+ function getSegNumberOfFramesFromDataset(multiframe) {
1998
+ const fromTag = Number(multiframe.NumberOfFrames);
1999
+ if (fromTag > 0) {
2000
+ return fromTag;
1952
2001
  }
1953
- return numSegments;
2002
+ const perFrame = multiframe.PerFrameFunctionalGroupsSequence;
2003
+ if (Array.isArray(perFrame) && perFrame.length > 0) {
2004
+ return perFrame.length;
2005
+ }
2006
+ return 1;
1954
2007
  }
1955
-
1956
- /**
1957
- * _createSegFromImages - description
1958
- *
1959
- * @param {Object[]} images An array of the cornerstone image objects.
1960
- * @param {Boolean} isMultiframe Whether the images are multiframe.
1961
- * @returns {Object} The Seg derived dataSet.
1962
- */
1963
- function _createSegFromImages(images, isMultiframe, options) {
1964
- const multiframe = getDatasetsFromImages(images, isMultiframe);
1965
- return new SegmentationDerivation([multiframe], options);
1966
- }
1967
-
1968
- /**
1969
- * generateToolState - Given a set of cornrstoneTools imageIds and a Segmentation buffer,
1970
- * derive cornerstoneTools toolState and brush metadata.
1971
- *
1972
- * @param {string[]} imageIds An array of the imageIds.
1973
- * @param {ArrayBuffer} arrayBuffer The SEG arrayBuffer.
1974
- * @param {*} metadataProvider
1975
- * @returns {Object} The toolState and an object from which the
1976
- * segment metadata can be derived.
1977
- */
1978
- function generateToolState(imageIds, arrayBuffer, metadataProvider) {
1979
- const dicomData = Segmentation_3X_DicomMessage.readFile(arrayBuffer);
1980
- const dataset = Segmentation_3X_DicomMetaDictionary.naturalizeDataset(dicomData.dict);
1981
- dataset._meta = Segmentation_3X_DicomMetaDictionary.namifyDataset(dicomData.meta);
1982
- const multiframe = Segmentation_3X_Normalizer.normalizeToDataset([dataset]);
1983
- const imagePlaneModule = metadataProvider.get('imagePlaneModule', imageIds[0]);
1984
- if (!imagePlaneModule) {
1985
- Segmentation_3X_cs3dLogger.warn('Insufficient metadata, imagePlaneModule missing.');
1986
- }
1987
- const ImageOrientationPatient = Array.isArray(imagePlaneModule.rowCosines) ? [...imagePlaneModule.rowCosines, ...imagePlaneModule.columnCosines] : [imagePlaneModule.rowCosines.x, imagePlaneModule.rowCosines.y, imagePlaneModule.rowCosines.z, imagePlaneModule.columnCosines.x, imagePlaneModule.columnCosines.y, imagePlaneModule.columnCosines.z];
1988
-
1989
- // Get IOP from ref series, compute supported orientations:
1990
- const validOrientations = getValidOrientations(ImageOrientationPatient);
1991
- const SharedFunctionalGroupsSequence = multiframe.SharedFunctionalGroupsSequence;
1992
- const sharedImageOrientationPatient = SharedFunctionalGroupsSequence.PlaneOrientationSequence ? SharedFunctionalGroupsSequence.PlaneOrientationSequence.ImageOrientationPatient : undefined;
1993
- const sliceLength = multiframe.Columns * multiframe.Rows;
1994
- const segMetadata = getSegmentMetadata(multiframe);
1995
- const pixelData = unpackPixelData(multiframe);
1996
- const PerFrameFunctionalGroupsSequence = multiframe.PerFrameFunctionalGroupsSequence;
1997
- const toolState = {};
1998
- let inPlane = true;
1999
- for (let i = 0; i < PerFrameFunctionalGroupsSequence.length; i++) {
2000
- const PerFrameFunctionalGroups = PerFrameFunctionalGroupsSequence[i];
2001
- const ImageOrientationPatientI = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
2002
- const pixelDataI2D = ndarray(new Uint8Array(pixelData.buffer, i * sliceLength, sliceLength), [multiframe.Rows, multiframe.Columns]);
2003
- const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations);
2004
- if (!alignedPixelDataI) {
2005
- Segmentation_3X_cs3dLogger.warn("This segmentation object is not in-plane with the source data. Bailing out of IO. It'd be better to render this with vtkjs. ");
2006
- inPlane = false;
2007
- break;
2008
- }
2009
- const segmentIndex = PerFrameFunctionalGroups.SegmentIdentificationSequence.ReferencedSegmentNumber - 1;
2010
- let SourceImageSequence;
2011
- if (SharedFunctionalGroupsSequence.DerivationImageSequence && SharedFunctionalGroupsSequence.DerivationImageSequence.SourceImageSequence) {
2012
- SourceImageSequence = SharedFunctionalGroupsSequence.DerivationImageSequence.SourceImageSequence[i];
2013
- } else {
2014
- SourceImageSequence = PerFrameFunctionalGroups.DerivationImageSequence.SourceImageSequence;
2008
+ function decodeRlePackBitsSegment(data, start, end, outLength) {
2009
+ const out = new Uint8Array(outLength);
2010
+ let outIndex = 0;
2011
+ let inIndex = start;
2012
+ while (inIndex < end && outIndex < outLength) {
2013
+ const n = data[inIndex++];
2014
+ if (n >= 0 && n <= 127) {
2015
+ for (let i = 0; i < n + 1 && outIndex < outLength; ++i) {
2016
+ out[outIndex++] = data[inIndex++] & 0xff;
2017
+ }
2018
+ } else if (n <= -1 && n >= -127) {
2019
+ const value = data[inIndex++] & 0xff;
2020
+ for (let j = 0; j < -n + 1 && outIndex < outLength; ++j) {
2021
+ out[outIndex++] = value;
2022
+ }
2015
2023
  }
2016
- const imageId = getImageIdOfSourceImage(SourceImageSequence, imageIds, metadataProvider);
2017
- addImageIdSpecificBrushToolState(toolState, imageId, segmentIndex, alignedPixelDataI);
2018
2024
  }
2019
- if (!inPlane) {
2020
- return;
2025
+ return out;
2026
+ }
2027
+ function decodeRleLosslessToPackedBytes(rleData, packedByteLength) {
2028
+ const frameData = rleData instanceof Uint8Array ? rleData : new Uint8Array(rleData);
2029
+ const header = new DataView(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2030
+ const data = new Int8Array(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2031
+ const numSegments = header.getInt32(0, true);
2032
+ if (numSegments !== 1) {
2033
+ throw new Error("Expected a single RLE segment for SEG re-encode, got ".concat(numSegments));
2021
2034
  }
2022
- return {
2023
- toolState,
2024
- segMetadata
2025
- };
2035
+ const start = header.getInt32(4, true);
2036
+ let end = header.getInt32(8, true);
2037
+ if (end === 0) {
2038
+ end = frameData.length;
2039
+ }
2040
+ return decodeRlePackBitsSegment(data, start, end, packedByteLength);
2026
2041
  }
2027
-
2028
- /**
2029
- * unpackPixelData - Unpacks bitpacked pixelData if the Segmentation is BINARY.
2030
- *
2031
- * @param {Object} multiframe The multiframe dataset.
2032
- * @return {Uint8Array} The unpacked pixelData.
2033
- */
2034
- function unpackPixelData(multiframe) {
2035
- const segType = multiframe.SegmentationType;
2036
- if (segType === 'BINARY') {
2037
- return BitArray.unpack(multiframe.PixelData);
2042
+ function decodeRleMultiByteFrame(rleData, samplesPerFrame, bitsAllocated) {
2043
+ const frameData = rleData instanceof Uint8Array ? rleData : new Uint8Array(rleData);
2044
+ const header = new DataView(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2045
+ const data = new Int8Array(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2046
+ const numSegments = header.getInt32(0, true);
2047
+ const bytesPerSample = Math.ceil(bitsAllocated / 8);
2048
+ if (numSegments !== bytesPerSample) {
2049
+ throw new Error("Expected ".concat(bytesPerSample, " RLE segment(s) for ").concat(bitsAllocated, "-bit SEG, got ").concat(numSegments));
2038
2050
  }
2039
- const pixelData = new Uint8Array(multiframe.PixelData);
2040
- const max = multiframe.MaximumFractionalValue;
2041
- const onlyMaxAndZero = pixelData.find(element => element !== 0 && element !== max) === undefined;
2042
- if (!onlyMaxAndZero) {
2043
- dcmjs_es/* .log.warn */.Rm.warn('This is a fractional segmentation, which is not currently supported.');
2044
- return;
2051
+ const segmentStart = index => header.getInt32(4 + index * 4, true);
2052
+ if (bitsAllocated <= 8) {
2053
+ return decodeRlePackBitsSegment(data, segmentStart(0), frameData.length, samplesPerFrame);
2045
2054
  }
2046
- dcmjs_es/* .log.warn */.Rm.warn('This segmentation object is actually binary... processing as such.');
2047
- return pixelData;
2055
+ const highStart = segmentStart(0);
2056
+ const lowStart = segmentStart(1);
2057
+ const highBytes = decodeRlePackBitsSegment(data, highStart, lowStart, samplesPerFrame);
2058
+ const lowBytes = decodeRlePackBitsSegment(data, lowStart, frameData.length, samplesPerFrame);
2059
+ const frame = new Uint16Array(samplesPerFrame);
2060
+ for (let i = 0; i < samplesPerFrame; i++) {
2061
+ frame[i] = (highBytes[i] << 8 | lowBytes[i]) & 0xffff;
2062
+ }
2063
+ return frame;
2048
2064
  }
2049
-
2050
- /**
2051
- * addImageIdSpecificBrushToolState - Adds brush pixel data to cornerstoneTools
2052
- * formatted toolState object.
2053
- *
2054
- * @param {Object} toolState The toolState object to modify
2055
- * @param {String} imageId The imageId of the toolState to add the data.
2056
- * @param {Number} segmentIndex The index of the segment data being added.
2057
- * @param {Ndarray} pixelData2D The pixelData in Ndarry 2D format.
2058
- */
2059
- function addImageIdSpecificBrushToolState(toolState, imageId, segmentIndex, pixelData2D) {
2060
- if (!toolState[imageId]) {
2061
- toolState[imageId] = {};
2062
- toolState[imageId].brush = {};
2063
- toolState[imageId].brush.data = [];
2064
- } else if (!toolState[imageId].brush) {
2065
- toolState[imageId].brush = {};
2066
- toolState[imageId].brush.data = [];
2067
- } else if (!toolState[imageId].brush.data) {
2068
- toolState[imageId].brush.data = [];
2065
+ function decodeSegFramesFromMultiframe(multiframe) {
2066
+ const rows = Number(multiframe.Rows);
2067
+ const columns = Number(multiframe.Columns);
2068
+ const samplesPerFrame = rows * columns;
2069
+ const bitsAllocated = Number(multiframe.BitsAllocated);
2070
+ const numberOfFrames = getSegNumberOfFramesFromDataset(multiframe);
2071
+ const transferSyntaxUid = getTransferSyntaxUid(multiframe);
2072
+ if (!multiframe.PixelData) {
2073
+ throw new Error('SEG dataset has no PixelData');
2069
2074
  }
2070
- toolState[imageId].brush.data[segmentIndex] = {};
2071
- const brushDataI = toolState[imageId].brush.data[segmentIndex];
2072
- brushDataI.pixelData = new Uint8Array(pixelData2D.data.length);
2073
- const cToolsPixelData = brushDataI.pixelData;
2074
- for (let p = 0; p < cToolsPixelData.length; p++) {
2075
- if (pixelData2D.data[p]) {
2076
- cToolsPixelData[p] = 1;
2077
- } else {
2078
- cToolsPixelData[p] = 0;
2075
+ if (bitsAllocated === 1) {
2076
+ if (transferSyntaxUid === RLE_LOSSLESS_TRANSFER_SYNTAX_UID) {
2077
+ const encodedFrames = Array.isArray(multiframe.PixelData) ? multiframe.PixelData : [multiframe.PixelData];
2078
+ const bytesPerFrame = getBytesForBinaryFrame(samplesPerFrame);
2079
+ const frames = [];
2080
+ for (let frameIndex = 0; frameIndex < numberOfFrames; frameIndex++) {
2081
+ const rleFrame = encodedFrames[frameIndex];
2082
+ if (!rleFrame) {
2083
+ frames.push(new Uint8Array(samplesPerFrame));
2084
+ continue;
2085
+ }
2086
+ const packed = decodeRleLosslessToPackedBytes(rleFrame, bytesPerFrame);
2087
+ frames.push(unpackBinaryFrameFromPacked(packed, samplesPerFrame));
2088
+ }
2089
+ return frames;
2079
2090
  }
2091
+ return getBitmapFramesFromDataset(multiframe).frames;
2080
2092
  }
2081
- }
2082
-
2083
- /**
2084
- * getImageIdOfSourceImage - Returns the Cornerstone imageId of the source image.
2085
- *
2086
- * @param {Object} SourceImageSequence Sequence describing the source image.
2087
- * @param {String[]} imageIds A list of imageIds.
2088
- * @param {Object} metadataProvider A Cornerstone metadataProvider to query
2089
- * metadata from imageIds.
2090
- * @return {String} The corresponding imageId.
2091
- */
2092
- function getImageIdOfSourceImage(SourceImageSequence, imageIds, metadataProvider) {
2093
- const ReferencedSOPInstanceUID = SourceImageSequence.ReferencedSOPInstanceUID,
2094
- ReferencedFrameNumber = SourceImageSequence.ReferencedFrameNumber;
2095
- return ReferencedFrameNumber ? getImageIdOfReferencedFrame(ReferencedSOPInstanceUID, ReferencedFrameNumber, imageIds, metadataProvider) : getImageIdOfReferencedSingleFramedSOPInstance(ReferencedSOPInstanceUID, imageIds, metadataProvider);
2096
- }
2097
-
2098
- /**
2099
- * getImageIdOfReferencedSingleFramedSOPInstance - Returns the imageId
2100
- * corresponding to the specified sopInstanceUid for single-frame images.
2101
- *
2102
- * @param {String} sopInstanceUid The sopInstanceUid of the desired image.
2103
- * @param {String[]} imageIds The list of imageIds.
2104
- * @param {Object} metadataProvider The metadataProvider to obtain sopInstanceUids
2105
- * from the cornerstone imageIds.
2106
- * @return {String} The imageId that corresponds to the sopInstanceUid.
2107
- */
2108
- function getImageIdOfReferencedSingleFramedSOPInstance(sopInstanceUid, imageIds, metadataProvider) {
2109
- return imageIds.find(imageId => {
2110
- const sopCommonModule = metadataProvider.get('sopCommonModule', imageId);
2111
- if (!sopCommonModule) {
2112
- return;
2093
+ if (transferSyntaxUid === RLE_LOSSLESS_TRANSFER_SYNTAX_UID) {
2094
+ const encodedFrames = Array.isArray(multiframe.PixelData) ? multiframe.PixelData : [multiframe.PixelData];
2095
+ const frames = [];
2096
+ for (let frameIndex = 0; frameIndex < numberOfFrames; frameIndex++) {
2097
+ const rleFrame = encodedFrames[frameIndex];
2098
+ if (!rleFrame) {
2099
+ frames.push(bitsAllocated <= 8 ? new Uint8Array(samplesPerFrame) : new Uint16Array(samplesPerFrame));
2100
+ continue;
2101
+ }
2102
+ frames.push(decodeRleMultiByteFrame(rleFrame, samplesPerFrame, bitsAllocated));
2113
2103
  }
2114
- return sopCommonModule.sopInstanceUID === sopInstanceUid;
2115
- });
2104
+ return frames;
2105
+ }
2106
+ return getBitmapFramesFromDataset(multiframe).frames;
2116
2107
  }
2117
-
2118
- /**
2119
- * getImageIdOfReferencedFrame - Returns the imageId corresponding to the
2120
- * specified sopInstanceUid and frameNumber for multi-frame images.
2121
- *
2122
- * @param {String} sopInstanceUid The sopInstanceUid of the desired image.
2123
- * @param {Number} frameNumber The frame number.
2124
- * @param {String} imageIds The list of imageIds.
2125
- * @param {Object} metadataProvider The metadataProvider to obtain sopInstanceUids
2126
- * from the cornerstone imageIds.
2127
- * @return {String} The imageId that corresponds to the sopInstanceUid.
2128
- */
2129
- function getImageIdOfReferencedFrame(sopInstanceUid, frameNumber, imageIds, metadataProvider) {
2130
- const imageId = imageIds.find(imageId => {
2131
- const sopCommonModule = metadataProvider.get('sopCommonModule', imageId);
2132
- if (!sopCommonModule) {
2133
- return;
2108
+ function createDecodeImageDataFromMultiframe(multiframe) {
2109
+ let cachedFrames = null;
2110
+ return async (_frameImageId, frameNumber) => {
2111
+ if (!cachedFrames) {
2112
+ cachedFrames = decodeSegFramesFromMultiframe(multiframe);
2134
2113
  }
2135
- const imageIdFrameNumber = Number(imageId.split('frame=')[1]);
2136
- return (
2137
- //frameNumber is zero indexed for cornerstoneDICOMImageLoader image Ids.
2138
- sopCommonModule.sopInstanceUID === sopInstanceUid && imageIdFrameNumber === frameNumber - 1
2139
- );
2140
- });
2141
- return imageId;
2142
- }
2143
-
2144
- /**
2145
- * getValidOrientations - returns an array of valid orientations.
2146
- *
2147
- * @param iop - The row (0..2) an column (3..5) direction cosines.
2148
- * @return An array of valid orientations.
2149
- */
2150
- function getValidOrientations(iop) {
2151
- const orientations = [];
2152
-
2153
- // [0, 1, 2]: 0, 0hf, 0vf
2154
- // [3, 4, 5]: 90, 90hf, 90vf
2155
- // [6, 7]: 180, 270
2156
-
2157
- orientations[0] = iop;
2158
- orientations[1] = flipIOP.h(iop);
2159
- orientations[2] = flipIOP.v(iop);
2160
- const iop90 = rotateDirectionCosinesInPlane(iop, Math.PI / 2);
2161
- orientations[3] = iop90;
2162
- orientations[4] = flipIOP.h(iop90);
2163
- orientations[5] = flipIOP.v(iop90);
2164
- orientations[6] = rotateDirectionCosinesInPlane(iop, Math.PI);
2165
- orientations[7] = rotateDirectionCosinesInPlane(iop, 1.5 * Math.PI);
2166
- return orientations;
2167
- }
2168
-
2169
- /**
2170
- * alignPixelDataWithSourceData -
2171
- *
2172
- * @param pixelData2D - The data to align.
2173
- * @param iop - The orientation of the image slice.
2174
- * @param orientations - An array of valid imageOrientationPatient values.
2175
- * @return The aligned pixelData.
2176
- */
2177
- function alignPixelDataWithSourceData(pixelData2D, iop, orientations) {
2178
- if (compareIOP(iop, orientations[0])) {
2179
- //Same orientation.
2180
- return pixelData2D;
2181
- } else if (compareIOP(iop, orientations[1])) {
2182
- //Flipped vertically.
2183
- return flipMatrix2D.v(pixelData2D);
2184
- } else if (compareIOP(iop, orientations[2])) {
2185
- //Flipped horizontally.
2186
- return flipMatrix2D.h(pixelData2D);
2187
- } else if (compareIOP(iop, orientations[3])) {
2188
- //Rotated 90 degrees.
2189
- return rotateMatrix902D(pixelData2D);
2190
- } else if (compareIOP(iop, orientations[4])) {
2191
- //Rotated 90 degrees and fliped horizontally.
2192
- return flipMatrix2D.h(rotateMatrix902D(pixelData2D));
2193
- } else if (compareIOP(iop, orientations[5])) {
2194
- //Rotated 90 degrees and fliped vertically.
2195
- return flipMatrix2D.v(rotateMatrix902D(pixelData2D));
2196
- } else if (compareIOP(iop, orientations[6])) {
2197
- //Rotated 180 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
2198
- return rotateMatrix902D(rotateMatrix902D(pixelData2D));
2199
- } else if (compareIOP(iop, orientations[7])) {
2200
- //Rotated 270 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
2201
- return rotateMatrix902D(rotateMatrix902D(rotateMatrix902D(pixelData2D)));
2202
- }
2203
- }
2204
- const dx = 1e-5;
2205
-
2206
- /**
2207
- * compareIOP - Returns true if iop1 and iop2 are equal
2208
- * within a tollerance, dx.
2209
- *
2210
- * @param iop1 - An ImageOrientationPatient array.
2211
- * @param iop2 - An ImageOrientationPatient array.
2212
- * @return True if iop1 and iop2 are equal.
2213
- */
2214
- function compareIOP(iop1, iop2) {
2215
- 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;
2216
- }
2217
- function getSegmentMetadata(multiframe) {
2218
- const data = [];
2219
- const segmentSequence = multiframe.SegmentSequence;
2220
- if (Array.isArray(segmentSequence)) {
2221
- for (let segIdx = 0; segIdx < segmentSequence.length; segIdx++) {
2222
- data.push(segmentSequence[segIdx]);
2114
+ const frame = cachedFrames[frameNumber - 1];
2115
+ if (!frame) {
2116
+ throw new Error("No SEG frame at index ".concat(frameNumber));
2223
2117
  }
2224
- } else {
2225
- // Only one segment, will be stored as an object.
2226
- data.push(segmentSequence);
2227
- }
2228
- return {
2229
- seriesInstanceUid: multiframe.ReferencedSeriesSequence.SeriesInstanceUID,
2230
- data
2118
+ return frame;
2231
2119
  };
2232
2120
  }
2233
-
2234
-
2235
-
2236
- ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/helpers/checkIfPerpendicular.js
2237
- function checkIfPerpendicular(iop1, iop2, tolerance) {
2238
- const absDotColumnCosines = Math.abs(iop1[0] * iop2[0] + iop1[1] * iop2[1] + iop1[2] * iop2[2]);
2239
- const absDotRowCosines = Math.abs(iop1[3] * iop2[3] + iop1[4] * iop2[4] + iop1[5] * iop2[5]);
2240
- return (absDotColumnCosines < tolerance || Math.abs(absDotColumnCosines - 1) < tolerance) && (absDotRowCosines < tolerance || Math.abs(absDotRowCosines - 1) < tolerance);
2121
+ function getBytesForBinaryFrame(numPixels) {
2122
+ return Math.ceil(numPixels / 8);
2241
2123
  }
2242
-
2243
-
2244
-
2245
- ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/helpers/checkOrientation.js
2246
-
2247
-
2248
-
2249
- function checkOrientation(multiframe, validOrientations, sourceDataDimensions, tolerance) {
2250
- const SharedFunctionalGroupsSequence = multiframe.SharedFunctionalGroupsSequence,
2251
- PerFrameFunctionalGroupsSequence = multiframe.PerFrameFunctionalGroupsSequence;
2252
- const sharedImageOrientationPatient = SharedFunctionalGroupsSequence.PlaneOrientationSequence ? SharedFunctionalGroupsSequence.PlaneOrientationSequence.ImageOrientationPatient : undefined;
2253
- const PerFrameFunctionalGroups = PerFrameFunctionalGroupsSequence[0];
2254
- const iopRaw = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
2255
- const iop = Array.isArray(iopRaw) ? iopRaw.map(Number) : iopRaw;
2256
- const inPlane = validOrientations.some(operation => esm.utilities.isEqual(iop, operation, tolerance));
2257
- if (inPlane) {
2258
- return 'Planar';
2124
+ function asUint8PixelData(pixelData) {
2125
+ if (pixelData instanceof Uint8Array) {
2126
+ return pixelData;
2259
2127
  }
2260
- if (checkIfPerpendicular(iop, validOrientations[0], tolerance) && sourceDataDimensions.includes(multiframe.Rows) && sourceDataDimensions.includes(multiframe.Columns)) {
2261
- return 'Perpendicular';
2128
+ if (pixelData instanceof ArrayBuffer) {
2129
+ return new Uint8Array(pixelData);
2262
2130
  }
2263
- return 'Oblique';
2264
- }
2265
-
2266
-
2267
-
2268
- // EXTERNAL MODULE: ../../node_modules/@babel/runtime/helpers/esm/objectWithoutProperties.js
2269
- var objectWithoutProperties = __webpack_require__(39850);
2270
- ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/Segmentation/perFrameFunctionalGroups.js
2271
-
2272
-
2273
-
2274
-
2275
- const _excluded = ["SegmentIdentificationSequence"];
2276
- function perFrameFunctionalGroups_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; }
2277
- function perFrameFunctionalGroups_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? perFrameFunctionalGroups_ownKeys(Object(t), !0).forEach(function (r) { (0,defineProperty/* ["default"] */.A)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : perFrameFunctionalGroups_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
2278
- const MetadataModules = esm.Enums.MetadataModules;
2279
-
2280
- /**
2281
- * Resolves the 1-based DICOM frame number referenced by an imageId.
2282
- *
2283
- * Prefer the metadata provider's own frame extraction when it offers one — it
2284
- * understands the full set of imageId shapes the host app produces (wadors
2285
- * `/frames/N` as well as `?frame=N` / `&frame=N`). Fall back to the core
2286
- * FrameRange helper (handles `/frames/N` and `frameNumber=N`) so that
2287
- * provider-agnostic callers still resolve multi-frame references. A one-off
2288
- * `/[?&]frame=/` regex silently drops the wadors form, so it must not be used.
2289
- *
2290
- * @param {string} imageId
2291
- * @param {object} metadata - metadata provider
2292
- * @returns {number|undefined}
2293
- */
2294
- function getReferencedFrameNumber(imageId, metadata) {
2295
- var _metadata$getFrameInf;
2296
- if (!imageId) {
2297
- return undefined;
2131
+ if (Array.isArray(pixelData)) {
2132
+ if (pixelData.length === 1) {
2133
+ return new Uint8Array(pixelData[0]);
2134
+ }
2135
+ throw new Error('Multiframe encapsulated PixelData fragments cannot be converted to binary frames for re-encoding');
2298
2136
  }
2299
- const providerFrame = metadata === null || metadata === void 0 || (_metadata$getFrameInf = metadata.getFrameInformationFromURL) === null || _metadata$getFrameInf === void 0 ? void 0 : _metadata$getFrameInf.call(metadata, imageId);
2300
- const frameNumber = providerFrame != null ? Number(providerFrame) : esm.utilities.FrameRange.imageIdToFrameStart(imageId);
2301
- return Number.isFinite(frameNumber) ? frameNumber : undefined;
2137
+ return new Uint8Array(pixelData);
2302
2138
  }
2303
-
2304
- /**
2305
- * Builds a SourceImageSequence item (ReferencedSOPInstanceUID + optional
2306
- * ReferencedFrameNumber) for a cornerstone image, using the shared frame
2307
- * extraction so all SEG export paths resolve multi-frame references identically.
2308
- *
2309
- * @param {{ imageId?: string }} image
2310
- * @param {object} metadata - metadata provider
2311
- * @returns {{ ReferencedSOPInstanceUID: string, ReferencedFrameNumber?: number }}
2312
- */
2313
- function getReferencedSourceImageSequenceItem(image, metadata) {
2314
- var _metadata$get;
2315
- const imageData = (metadata === null || metadata === void 0 || (_metadata$get = metadata.get) === null || _metadata$get === void 0 ? void 0 : _metadata$get.call(metadata, MetadataModules.IMAGE_DATA, image === null || image === void 0 ? void 0 : image.imageId)) || {};
2316
- const referencedFrameNumber = getReferencedFrameNumber(image === null || image === void 0 ? void 0 : image.imageId, metadata);
2317
- const item = {
2318
- ReferencedSOPInstanceUID: imageData.SOPInstanceUID
2319
- };
2320
- if (Number.isFinite(referencedFrameNumber) && referencedFrameNumber > 0) {
2321
- item.ReferencedFrameNumber = referencedFrameNumber;
2139
+ function normalizeBinaryFrameTo01(frame) {
2140
+ const normalized = new Uint8Array(frame.length);
2141
+ for (let i = 0; i < frame.length; i++) {
2142
+ normalized[i] = frame[i] ? 1 : 0;
2322
2143
  }
2323
- return item;
2144
+ return normalized;
2324
2145
  }
2325
- function normalizeSharedFunctionalGroupsSequence(dataset) {
2326
- const shared = dataset.SharedFunctionalGroupsSequence;
2327
- if (Array.isArray(shared) && shared.length > 0) {
2328
- dataset.SharedFunctionalGroupsSequence = shared[0];
2329
- } else if (!shared || typeof shared !== 'object') {
2330
- dataset.SharedFunctionalGroupsSequence = {};
2146
+ function unpackBinaryFrameFromPacked(packed, samplesPerFrame) {
2147
+ const frame = new Uint8Array(samplesPerFrame);
2148
+ for (let i = 0; i < samplesPerFrame; i++) {
2149
+ const bytePos = i >> 3;
2150
+ const bitPos = i % 8;
2151
+ frame[i] = packed[bytePos] & 1 << bitPos ? 1 : 0;
2331
2152
  }
2153
+ return frame;
2332
2154
  }
2333
-
2334
- /**
2335
- * @param {object} dataset - SEG dataset
2336
- * @param {Array<{
2337
- * referencedSegmentNumber?: number,
2338
- * sourceImageSequenceItem: { ReferencedSOPInstanceUID: string, ReferencedFrameNumber?: number },
2339
- * planeOrientationSequence?: object,
2340
- * planePositionSequence?: object,
2341
- * }>} frames
2342
- *
2343
- * `referencedSegmentNumber` drives the per-frame `SegmentIdentificationSequence`
2344
- * macro (one segment per frame — BINARY SEGs). Omit it for LABELMAP SEGs: there a
2345
- * single frame carries many segment labels as pixel values, so the standard
2346
- * forbids the macro and a fixed `ReferencedSegmentNumber` would be wrong for any
2347
- * label other than the one hard-coded.
2348
- */
2349
- function applyPerFrameFunctionalGroups(dataset, frames) {
2350
- normalizeSharedFunctionalGroupsSequence(dataset);
2351
- const validFrames = frames.filter(frame => {
2352
- var _frame$sourceImageSeq;
2353
- return frame === null || frame === void 0 || (_frame$sourceImageSeq = frame.sourceImageSequenceItem) === null || _frame$sourceImageSeq === void 0 ? void 0 : _frame$sourceImageSeq.ReferencedSOPInstanceUID;
2354
- });
2355
- const existing = dataset.PerFrameFunctionalGroupsSequence;
2356
- const existingList = Array.isArray(existing) ? existing : [];
2357
- const nextSequence = validFrames.map((frame, index) => {
2358
- const prior = existingList[index] && typeof existingList[index] === 'object' ? existingList[index] : {};
2359
-
2360
- // Drop any inherited SegmentIdentificationSequence when this frame has no
2361
- // referencedSegmentNumber (LABELMAP path) so the macro is truly absent.
2362
- prior.SegmentIdentificationSequence;
2363
- const priorRest = (0,objectWithoutProperties/* ["default"] */.A)(prior, _excluded);
2364
- const group = perFrameFunctionalGroups_objectSpread(perFrameFunctionalGroups_objectSpread({}, priorRest), {}, {
2365
- DerivationImageSequence: [{
2366
- SourceImageSequence: [frame.sourceImageSequenceItem]
2367
- }]
2368
- });
2369
- if (frame.referencedSegmentNumber != null) {
2370
- group.SegmentIdentificationSequence = {
2371
- ReferencedSegmentNumber: frame.referencedSegmentNumber
2372
- };
2373
- }
2374
- if (frame.planeOrientationSequence) {
2375
- group.PlaneOrientationSequence = frame.planeOrientationSequence;
2376
- }
2377
- if (frame.planePositionSequence) {
2378
- group.PlanePositionSequence = frame.planePositionSequence;
2379
- }
2380
- return group;
2381
- });
2382
- dataset.PerFrameFunctionalGroupsSequence = nextSequence;
2383
- dataset.NumberOfFrames = nextSequence.length;
2384
- }
2385
-
2386
-
2387
-
2388
- ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/encodePixelData.js
2389
-
2390
-
2391
- const RLE_LOSSLESS_TRANSFER_SYNTAX_UID = '1.2.840.10008.1.2.5';
2392
- const EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID = dcmjs_es/* .constants.EXPLICIT_LITTLE_ENDIAN */.AA.EXPLICIT_LITTLE_ENDIAN;
2393
- function getTransferSyntaxUid(multiframe) {
2394
- var _meta$TransferSyntaxU;
2395
- const meta = multiframe._meta;
2396
- const fromMeta = meta === null || meta === void 0 || (_meta$TransferSyntaxU = meta.TransferSyntaxUID) === null || _meta$TransferSyntaxU === void 0 || (_meta$TransferSyntaxU = _meta$TransferSyntaxU.Value) === null || _meta$TransferSyntaxU === void 0 ? void 0 : _meta$TransferSyntaxU[0];
2397
- if (fromMeta) {
2398
- return fromMeta;
2399
- }
2400
- if (typeof multiframe.TransferSyntaxUID === 'string') {
2401
- return multiframe.TransferSyntaxUID;
2155
+ function unpackBinaryFrameFromContinuousPack(packed, samplesPerFrame, frameIndex) {
2156
+ const frame = new Uint8Array(samplesPerFrame);
2157
+ const bitOffset = frameIndex * samplesPerFrame;
2158
+ for (let i = 0; i < samplesPerFrame; i++) {
2159
+ const bitIndex = bitOffset + i;
2160
+ const bytePos = bitIndex >> 3;
2161
+ const bitPos = bitIndex % 8;
2162
+ frame[i] = packed[bytePos] & 1 << bitPos ? 1 : 0;
2402
2163
  }
2403
- return EXPLICIT_VR_LITTLE_ENDIAN_TRANSFER_SYNTAX_UID;
2164
+ return frame;
2404
2165
  }
2405
- function getSegNumberOfFramesFromDataset(multiframe) {
2406
- const fromTag = Number(multiframe.NumberOfFrames);
2407
- if (fromTag > 0) {
2408
- return fromTag;
2409
- }
2410
- const perFrame = multiframe.PerFrameFunctionalGroupsSequence;
2411
- if (Array.isArray(perFrame) && perFrame.length > 0) {
2412
- return perFrame.length;
2413
- }
2414
- return 1;
2415
- }
2416
- function decodeRlePackBitsSegment(data, start, end, outLength) {
2417
- const out = new Uint8Array(outLength);
2418
- let outIndex = 0;
2419
- let inIndex = start;
2420
- while (inIndex < end && outIndex < outLength) {
2421
- const n = data[inIndex++];
2422
- if (n >= 0 && n <= 127) {
2423
- for (let i = 0; i < n + 1 && outIndex < outLength; ++i) {
2424
- out[outIndex++] = data[inIndex++] & 0xff;
2425
- }
2426
- } else if (n <= -1 && n >= -127) {
2427
- const value = data[inIndex++] & 0xff;
2428
- for (let j = 0; j < -n + 1 && outIndex < outLength; ++j) {
2429
- out[outIndex++] = value;
2430
- }
2431
- }
2432
- }
2433
- return out;
2434
- }
2435
- function decodeRleLosslessToPackedBytes(rleData, packedByteLength) {
2436
- const frameData = rleData instanceof Uint8Array ? rleData : new Uint8Array(rleData);
2437
- const header = new DataView(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2438
- const data = new Int8Array(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2439
- const numSegments = header.getInt32(0, true);
2440
- if (numSegments !== 1) {
2441
- throw new Error("Expected a single RLE segment for SEG re-encode, got ".concat(numSegments));
2442
- }
2443
- const start = header.getInt32(4, true);
2444
- let end = header.getInt32(8, true);
2445
- if (end === 0) {
2446
- end = frameData.length;
2447
- }
2448
- return decodeRlePackBitsSegment(data, start, end, packedByteLength);
2449
- }
2450
- function decodeRleMultiByteFrame(rleData, samplesPerFrame, bitsAllocated) {
2451
- const frameData = rleData instanceof Uint8Array ? rleData : new Uint8Array(rleData);
2452
- const header = new DataView(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2453
- const data = new Int8Array(frameData.buffer, frameData.byteOffset, frameData.byteLength);
2454
- const numSegments = header.getInt32(0, true);
2455
- const bytesPerSample = Math.ceil(bitsAllocated / 8);
2456
- if (numSegments !== bytesPerSample) {
2457
- throw new Error("Expected ".concat(bytesPerSample, " RLE segment(s) for ").concat(bitsAllocated, "-bit SEG, got ").concat(numSegments));
2458
- }
2459
- const segmentStart = index => header.getInt32(4 + index * 4, true);
2460
- if (bitsAllocated <= 8) {
2461
- return decodeRlePackBitsSegment(data, segmentStart(0), frameData.length, samplesPerFrame);
2462
- }
2463
- const highStart = segmentStart(0);
2464
- const lowStart = segmentStart(1);
2465
- const highBytes = decodeRlePackBitsSegment(data, highStart, lowStart, samplesPerFrame);
2466
- const lowBytes = decodeRlePackBitsSegment(data, lowStart, frameData.length, samplesPerFrame);
2467
- const frame = new Uint16Array(samplesPerFrame);
2468
- for (let i = 0; i < samplesPerFrame; i++) {
2469
- frame[i] = (highBytes[i] << 8 | lowBytes[i]) & 0xffff;
2470
- }
2471
- return frame;
2472
- }
2473
- function decodeSegFramesFromMultiframe(multiframe) {
2474
- const rows = Number(multiframe.Rows);
2475
- const columns = Number(multiframe.Columns);
2476
- const samplesPerFrame = rows * columns;
2477
- const bitsAllocated = Number(multiframe.BitsAllocated);
2478
- const numberOfFrames = getSegNumberOfFramesFromDataset(multiframe);
2479
- const transferSyntaxUid = getTransferSyntaxUid(multiframe);
2480
- if (!multiframe.PixelData) {
2481
- throw new Error('SEG dataset has no PixelData');
2482
- }
2483
- if (bitsAllocated === 1) {
2484
- if (transferSyntaxUid === RLE_LOSSLESS_TRANSFER_SYNTAX_UID) {
2485
- const encodedFrames = Array.isArray(multiframe.PixelData) ? multiframe.PixelData : [multiframe.PixelData];
2486
- const bytesPerFrame = getBytesForBinaryFrame(samplesPerFrame);
2487
- const frames = [];
2488
- for (let frameIndex = 0; frameIndex < numberOfFrames; frameIndex++) {
2489
- const rleFrame = encodedFrames[frameIndex];
2490
- if (!rleFrame) {
2491
- frames.push(new Uint8Array(samplesPerFrame));
2492
- continue;
2493
- }
2494
- const packed = decodeRleLosslessToPackedBytes(rleFrame, bytesPerFrame);
2495
- frames.push(unpackBinaryFrameFromPacked(packed, samplesPerFrame));
2496
- }
2497
- return frames;
2498
- }
2499
- return getBitmapFramesFromDataset(multiframe).frames;
2500
- }
2501
- if (transferSyntaxUid === RLE_LOSSLESS_TRANSFER_SYNTAX_UID) {
2502
- const encodedFrames = Array.isArray(multiframe.PixelData) ? multiframe.PixelData : [multiframe.PixelData];
2503
- const frames = [];
2504
- for (let frameIndex = 0; frameIndex < numberOfFrames; frameIndex++) {
2505
- const rleFrame = encodedFrames[frameIndex];
2506
- if (!rleFrame) {
2507
- frames.push(bitsAllocated <= 8 ? new Uint8Array(samplesPerFrame) : new Uint16Array(samplesPerFrame));
2508
- continue;
2509
- }
2510
- frames.push(decodeRleMultiByteFrame(rleFrame, samplesPerFrame, bitsAllocated));
2511
- }
2512
- return frames;
2513
- }
2514
- return getBitmapFramesFromDataset(multiframe).frames;
2515
- }
2516
- function createDecodeImageDataFromMultiframe(multiframe) {
2517
- let cachedFrames = null;
2518
- return async (_frameImageId, frameNumber) => {
2519
- if (!cachedFrames) {
2520
- cachedFrames = decodeSegFramesFromMultiframe(multiframe);
2521
- }
2522
- const frame = cachedFrames[frameNumber - 1];
2523
- if (!frame) {
2524
- throw new Error("No SEG frame at index ".concat(frameNumber));
2525
- }
2526
- return frame;
2527
- };
2528
- }
2529
- function getBytesForBinaryFrame(numPixels) {
2530
- return Math.ceil(numPixels / 8);
2531
- }
2532
- function asUint8PixelData(pixelData) {
2533
- if (pixelData instanceof Uint8Array) {
2534
- return pixelData;
2535
- }
2536
- if (pixelData instanceof ArrayBuffer) {
2537
- return new Uint8Array(pixelData);
2538
- }
2539
- if (Array.isArray(pixelData)) {
2540
- if (pixelData.length === 1) {
2541
- return new Uint8Array(pixelData[0]);
2542
- }
2543
- throw new Error('Multiframe encapsulated PixelData fragments cannot be converted to binary frames for re-encoding');
2544
- }
2545
- return new Uint8Array(pixelData);
2546
- }
2547
- function normalizeBinaryFrameTo01(frame) {
2548
- const normalized = new Uint8Array(frame.length);
2549
- for (let i = 0; i < frame.length; i++) {
2550
- normalized[i] = frame[i] ? 1 : 0;
2551
- }
2552
- return normalized;
2553
- }
2554
- function unpackBinaryFrameFromPacked(packed, samplesPerFrame) {
2555
- const frame = new Uint8Array(samplesPerFrame);
2556
- for (let i = 0; i < samplesPerFrame; i++) {
2557
- const bytePos = i >> 3;
2558
- const bitPos = i % 8;
2559
- frame[i] = packed[bytePos] & 1 << bitPos ? 1 : 0;
2560
- }
2561
- return frame;
2562
- }
2563
- function unpackBinaryFrameFromContinuousPack(packed, samplesPerFrame, frameIndex) {
2564
- const frame = new Uint8Array(samplesPerFrame);
2565
- const bitOffset = frameIndex * samplesPerFrame;
2566
- for (let i = 0; i < samplesPerFrame; i++) {
2567
- const bitIndex = bitOffset + i;
2568
- const bytePos = bitIndex >> 3;
2569
- const bitPos = bitIndex % 8;
2570
- frame[i] = packed[bytePos] & 1 << bitPos ? 1 : 0;
2571
- }
2572
- return frame;
2573
- }
2574
- function getBitmapFramesFromDataset(dataset) {
2575
- const numberOfFrames = Number(dataset.NumberOfFrames) || 1;
2576
- const rows = Number(dataset.Rows);
2577
- const columns = Number(dataset.Columns);
2578
- const samplesPerFrame = rows * columns;
2579
- const bitsAllocated = Number(dataset.BitsAllocated);
2580
- if (!dataset.PixelData) {
2581
- throw new Error('Bitmap SEG dataset has no PixelData');
2166
+ function getBitmapFramesFromDataset(dataset) {
2167
+ const numberOfFrames = Number(dataset.NumberOfFrames) || 1;
2168
+ const rows = Number(dataset.Rows);
2169
+ const columns = Number(dataset.Columns);
2170
+ const samplesPerFrame = rows * columns;
2171
+ const bitsAllocated = Number(dataset.BitsAllocated);
2172
+ if (!dataset.PixelData) {
2173
+ throw new Error('Bitmap SEG dataset has no PixelData');
2582
2174
  }
2583
2175
  if (bitsAllocated === 1) {
2584
2176
  const buffer = asUint8PixelData(dataset.PixelData);
@@ -2846,17 +2438,14 @@ var Events_Events;
2846
2438
 
2847
2439
 
2848
2440
 
2441
+
2442
+
2849
2443
  const Segmentation_4X_cs3dLogger = esm.utilities.logger.adaptersLog.getLogger('Cornerstone.Segmentation_4X');
2850
- const Segmentation_4X_utilities$orientatio = dcmjs_es/* .utilities.orientation */.BF.orientation,
2851
- Segmentation_4X_rotateDirectionCosinesInPlane = Segmentation_4X_utilities$orientatio.rotateDirectionCosinesInPlane,
2852
- Segmentation_4X_flipIOP = Segmentation_4X_utilities$orientatio.flipImageOrientationPatient,
2853
- Segmentation_4X_flipMatrix2D = Segmentation_4X_utilities$orientatio.flipMatrix2D,
2854
- Segmentation_4X_rotateMatrix902D = Segmentation_4X_utilities$orientatio.rotateMatrix902D;
2855
- const Segmentation_4X_BitArray = dcmjs_es/* .data.BitArray */.p.BitArray,
2444
+ const BitArray = dcmjs_es/* .data.BitArray */.p.BitArray,
2856
2445
  Segmentation_4X_DicomMessage = dcmjs_es/* .data.DicomMessage */.p.DicomMessage,
2857
2446
  Segmentation_4X_DicomMetaDictionary = dcmjs_es/* .data.DicomMetaDictionary */.p.DicomMetaDictionary;
2858
2447
  const Segmentation_4X_Normalizer = dcmjs_es/* .normalizers.Normalizer */.z8.Normalizer;
2859
- const Segmentation_4X_SegmentationDerivation = dcmjs_es/* .derivations.Segmentation */.h4.Segmentation;
2448
+ const SegmentationDerivation = dcmjs_es/* .derivations.Segmentation */.h4.Segmentation;
2860
2449
  const _utilities$compressio = dcmjs_es/* .utilities.compression */.BF.compression,
2861
2450
  encode = _utilities$compressio.encode,
2862
2451
  decode = _utilities$compressio.decode;
@@ -2885,13 +2474,22 @@ const generateSegmentationDefaultOptions = {
2885
2474
  * @param {Object} userOptions Options to pass to the segmentation derivation and `fillSegmentation`.
2886
2475
  * @returns {Blob}
2887
2476
  */
2888
- function Segmentation_4X_generateSegmentation(images, inputLabelmaps3D) {
2477
+ function generateSegmentation(images, inputLabelmaps3D) {
2889
2478
  let userOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2890
2479
  const isMultiframe = isMultiframeImage(images[0]);
2891
- const segmentation = Segmentation_4X_createSegFromImages(images, isMultiframe, userOptions);
2480
+ const segmentation = _createSegFromImages(images, isMultiframe, userOptions);
2892
2481
  return fillSegmentation(segmentation, inputLabelmaps3D, userOptions);
2893
2482
  }
2894
2483
 
2484
+ /**
2485
+ * The segment index of a voxel value of one labelmap3D. A value that is not in
2486
+ * `labelmap3D.labelToSegmentIndex` is its own segment index.
2487
+ */
2488
+ function getSegmentIndexForLabel(labelmap3D, labelValue) {
2489
+ var _labelmap3D$labelToSe, _labelmap3D$labelToSe2;
2490
+ 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;
2491
+ }
2492
+
2895
2493
  /**
2896
2494
  * The set of non-zero segment values actually present in a frame's pixel data,
2897
2495
  * collected in a single pass. `segmentsOnLabelmap` can be stale, so presence is
@@ -2917,6 +2515,12 @@ function segmentsPresentInFrame(pixelData) {
2917
2515
  *
2918
2516
  * @param segmentation - The segmentation object to be filled.
2919
2517
  * @param inputLabelmaps3D - An array of 3D labelmaps, or a single 3D labelmap.
2518
+ * The voxels of a labelmap3D hold label values. `labelToSegmentIndex` maps a
2519
+ * label value to its segment index, for a layer that stores a segment under
2520
+ * another label value; a value that is not in the map is its own segment
2521
+ * index. `segmentsOnLabelmap` of each labelmap2D lists label values. Two
2522
+ * label values with the same segment index, in one labelmap3D or in two,
2523
+ * give one SEG segment.
2920
2524
  * @param userOptions - Optional configuration settings. Will override the default options.
2921
2525
  * - `transferSyntaxUid` — the output transfer syntax. Defaults to RLE Lossless
2922
2526
  * (`1.2.840.10008.1.2.5`); Explicit VR Little Endian
@@ -2930,7 +2534,7 @@ function segmentsPresentInFrame(pixelData) {
2930
2534
  * @returns {object} The filled segmentation object.
2931
2535
  */
2932
2536
  function fillSegmentation(segmentation, inputLabelmaps3D) {
2933
- var _ref, _options$transferSynt;
2537
+ var _segmentation$dataset, _segmentation$dataset2, _ref, _options$transferSynt;
2934
2538
  let userOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
2935
2539
  let images = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
2936
2540
  let metadata = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
@@ -2938,79 +2542,68 @@ function fillSegmentation(segmentation, inputLabelmaps3D) {
2938
2542
 
2939
2543
  // Use another variable so we don't redefine labelmaps3D.
2940
2544
  const labelmaps3D = Array.isArray(inputLabelmaps3D) ? inputLabelmaps3D : [inputLabelmaps3D];
2941
- const referencedFramesPerLabelmap = [];
2942
2545
  const frameDescriptors = [];
2546
+ const entriesBySegmentIndex = new Map();
2943
2547
  for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
2944
2548
  const labelmap3D = labelmaps3D[labelmapIndex];
2945
2549
  const labelmaps2D = labelmap3D.labelmaps2D,
2946
2550
  segmentMetadata = labelmap3D.metadata;
2947
- const referencedFramesPerSegment = [];
2948
- for (let i = 1; i < segmentMetadata.length; i++) {
2949
- if (segmentMetadata[i]) {
2950
- referencedFramesPerSegment[i] = [];
2951
- }
2952
- }
2953
2551
  for (let i = 0; i < labelmaps2D.length; i++) {
2954
2552
  const labelmap2D = labelmaps2D[i];
2955
- if (!(labelmap2D !== null && labelmap2D !== void 0 && labelmap2D.pixelData)) {
2553
+ if (!labelmap2D) {
2956
2554
  continue;
2957
2555
  }
2958
2556
  const segmentsOnLabelmap = labelmap2D.segmentsOnLabelmap;
2959
- const presentSegments = segmentsPresentInFrame(labelmap2D.pixelData);
2960
- segmentsOnLabelmap.forEach(segmentIndex => {
2961
- if (segmentIndex !== 0 && segmentMetadata[segmentIndex] && referencedFramesPerSegment[segmentIndex] && presentSegments.has(segmentIndex)) {
2962
- referencedFramesPerSegment[segmentIndex].push(i);
2557
+ segmentsPresentInFrame(labelmap2D.pixelData).forEach(labelValue => {
2558
+ const segmentIndex = getSegmentIndexForLabel(labelmap3D, labelValue);
2559
+ if (!segmentMetadata[segmentIndex] || !segmentsOnLabelmap.includes(labelValue)) {
2560
+ return;
2561
+ }
2562
+ if (!entriesBySegmentIndex.has(segmentIndex)) {
2563
+ entriesBySegmentIndex.set(segmentIndex, {
2564
+ segmentIndex,
2565
+ metadata: segmentMetadata[segmentIndex],
2566
+ sources: [],
2567
+ frameIndices: new Set()
2568
+ });
2569
+ }
2570
+ const entry = entriesBySegmentIndex.get(segmentIndex);
2571
+ if (!entry.sources.some(source => source.labelmap3D === labelmap3D && source.labelValue === labelValue)) {
2572
+ entry.sources.push({
2573
+ labelmap3D,
2574
+ labelValue
2575
+ });
2963
2576
  }
2577
+ entry.frameIndices.add(i);
2964
2578
  });
2965
2579
  }
2966
- referencedFramesPerLabelmap[labelmapIndex] = referencedFramesPerSegment;
2967
- }
2968
- let numberOfFrames = 0;
2969
- for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
2970
- const referencedFramesPerSegment = referencedFramesPerLabelmap[labelmapIndex];
2971
- const labelmap3D = labelmaps3D[labelmapIndex];
2972
- const segmentMetadata = labelmap3D.metadata;
2973
- for (let segmentIndex = 1; segmentIndex < referencedFramesPerSegment.length; segmentIndex++) {
2974
- const referencedFrameIndicies = referencedFramesPerSegment[segmentIndex];
2975
- if (!(referencedFrameIndicies !== null && referencedFrameIndicies !== void 0 && referencedFrameIndicies.length) || !segmentMetadata[segmentIndex]) {
2976
- continue;
2977
- }
2978
- const labelmaps = _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies);
2979
- if (!labelmaps.length || !labelmaps.some(frame => (frame === null || frame === void 0 ? void 0 : frame.length) && frame.some(v => v !== 0))) {
2980
- continue;
2981
- }
2982
- numberOfFrames += referencedFrameIndicies.length;
2983
- }
2984
2580
  }
2581
+
2582
+ // dcmjs numbers the segments in the order they are added.
2583
+ const segmentEntries = [...entriesBySegmentIndex.values()].sort((a, b) => a.segmentIndex - b.segmentIndex);
2584
+ const numberOfFrames = segmentEntries.reduce((total, entry) => total + entry.frameIndices.size, 0);
2985
2585
  if (numberOfFrames === 0) {
2986
2586
  throw new Error('No non-empty segmentation frames found for SEG export');
2987
2587
  }
2988
2588
  segmentation.setNumberOfFrames(numberOfFrames);
2989
- for (let labelmapIndex = 0; labelmapIndex < labelmaps3D.length; labelmapIndex++) {
2990
- const referencedFramesPerSegment = referencedFramesPerLabelmap[labelmapIndex];
2991
- const labelmap3D = labelmaps3D[labelmapIndex];
2992
- const segmentMetadata = labelmap3D.metadata;
2993
- for (let segmentIndex = 1; segmentIndex < referencedFramesPerSegment.length; segmentIndex++) {
2994
- const referencedFrameIndicies = referencedFramesPerSegment[segmentIndex];
2995
- if (!(referencedFrameIndicies !== null && referencedFrameIndicies !== void 0 && referencedFrameIndicies.length) || !segmentMetadata[segmentIndex]) {
2996
- continue;
2997
- }
2998
- const labelmaps = _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies);
2999
- if (!labelmaps.length || !labelmaps.some(frame => (frame === null || frame === void 0 ? void 0 : frame.length) && frame.some(v => v !== 0))) {
3000
- continue;
3001
- }
2589
+ 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;
2590
+ segmentEntries.forEach((entry, entryIndex) => {
2591
+ const referencedFrameIndicies = [...entry.frameIndices].sort((a, b) => a - b);
2592
+ const _getSegmentLabelmaps2 = _getSegmentLabelmaps(entry.sources, referencedFrameIndicies),
2593
+ labelmaps = _getSegmentLabelmaps2.labelmaps,
2594
+ labelValue = _getSegmentLabelmaps2.labelValue;
3002
2595
 
3003
- // Frame numbers start from 1.
3004
- const referencedFrameNumbers = referencedFrameIndicies.map(element => element + 1);
3005
- referencedFrameNumbers.forEach(frameNumber => {
3006
- frameDescriptors.push({
3007
- referencedSegmentNumber: segmentIndex,
3008
- sourceFrameIndex: frameNumber - 1
3009
- });
2596
+ // Frame numbers start from 1.
2597
+ const referencedFrameNumbers = referencedFrameIndicies.map(element => element + 1);
2598
+ segmentation.addSegmentFromLabelmap(entry.metadata, labelmaps, labelValue, referencedFrameNumbers);
2599
+ const referencedSegmentNumber = firstSegmentNumber + entryIndex;
2600
+ referencedFrameNumbers.forEach(frameNumber => {
2601
+ frameDescriptors.push({
2602
+ referencedSegmentNumber,
2603
+ sourceFrameIndex: frameNumber - 1
3010
2604
  });
3011
- segmentation.addSegmentFromLabelmap(segmentMetadata[segmentIndex], labelmaps, segmentIndex, referencedFrameNumbers);
3012
- }
3013
- }
2605
+ });
2606
+ });
3014
2607
  if (frameDescriptors.length && images !== null && images !== void 0 && images.length && metadata) {
3015
2608
  // Every SEG frame must reference a resolvable source SOP Instance UID.
3016
2609
  // Reject rather than silently dropping frames: a dropped frame would make
@@ -3089,6 +2682,48 @@ function fillSegmentation(segmentation, inputLabelmaps3D) {
3089
2682
  }
3090
2683
  return segmentation;
3091
2684
  }
2685
+
2686
+ /**
2687
+ * The frames of one SEG segment and the value that marks the segment in them.
2688
+ * A segment with one source uses the frames of its labelmap3D. A segment with
2689
+ * more sources gets new binary frames, with 1 where any source has its label
2690
+ * value.
2691
+ */
2692
+ function _getSegmentLabelmaps(sources, referencedFrameIndicies) {
2693
+ if (sources.length === 1) {
2694
+ const _sources = (0,slicedToArray/* ["default"] */.A)(sources, 1),
2695
+ _sources$ = _sources[0],
2696
+ labelmap3D = _sources$.labelmap3D,
2697
+ labelValue = _sources$.labelValue;
2698
+ return {
2699
+ labelmaps: _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies),
2700
+ labelValue
2701
+ };
2702
+ }
2703
+ const labelmaps = referencedFrameIndicies.map(frameIndex => {
2704
+ let merged;
2705
+ sources.forEach(_ref2 => {
2706
+ var _labelmap3D$labelmaps;
2707
+ let labelmap3D = _ref2.labelmap3D,
2708
+ labelValue = _ref2.labelValue;
2709
+ const pixelData = (_labelmap3D$labelmaps = labelmap3D.labelmaps2D[frameIndex]) === null || _labelmap3D$labelmaps === void 0 ? void 0 : _labelmap3D$labelmaps.pixelData;
2710
+ if (!pixelData) {
2711
+ return;
2712
+ }
2713
+ merged || (merged = new Uint8Array(pixelData.length));
2714
+ for (let i = 0; i < pixelData.length; i++) {
2715
+ if (pixelData[i] === labelValue) {
2716
+ merged[i] = 1;
2717
+ }
2718
+ }
2719
+ });
2720
+ return merged;
2721
+ });
2722
+ return {
2723
+ labelmaps,
2724
+ labelValue: 1
2725
+ };
2726
+ }
3092
2727
  function _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameIndicies) {
3093
2728
  const labelmaps2D = labelmap3D.labelmaps2D;
3094
2729
  const labelmaps = [];
@@ -3106,9 +2741,9 @@ function _getLabelmapsFromReferencedFrameIndicies(labelmap3D, referencedFrameInd
3106
2741
  * @param {Boolean} isMultiframe Whether the images are multiframe.
3107
2742
  * @returns {Object} The Seg derived dataSet.
3108
2743
  */
3109
- function Segmentation_4X_createSegFromImages(images, isMultiframe, options) {
2744
+ function _createSegFromImages(images, isMultiframe, options) {
3110
2745
  const multiframe = getDatasetsFromImages(images, isMultiframe);
3111
- return new Segmentation_4X_SegmentationDerivation([multiframe], options);
2746
+ return new SegmentationDerivation([multiframe], options);
3112
2747
  }
3113
2748
 
3114
2749
  /**
@@ -3126,7 +2761,7 @@ function Segmentation_4X_createSegFromImages(images, isMultiframe, options) {
3126
2761
  * @return {[][][]} 3D list containing the track of segments per frame for each labelMap
3127
2762
  * (available only for the overlapping case).
3128
2763
  */
3129
- async function Segmentation_4X_generateToolState(referencedImageIds, arrayBuffer, metadataProvider, options) {
2764
+ async function generateToolState(referencedImageIds, arrayBuffer, metadataProvider, options) {
3130
2765
  const _options$skipOverlapp = options.skipOverlapping,
3131
2766
  skipOverlapping = _options$skipOverlapp === void 0 ? false : _options$skipOverlapp,
3132
2767
  _options$tolerance = options.tolerance,
@@ -3152,9 +2787,9 @@ async function Segmentation_4X_generateToolState(referencedImageIds, arrayBuffer
3152
2787
  const ImageOrientationPatient = Array.isArray(imagePlaneModule.rowCosines) ? [...imagePlaneModule.rowCosines, ...imagePlaneModule.columnCosines] : [imagePlaneModule.rowCosines.x, imagePlaneModule.rowCosines.y, imagePlaneModule.rowCosines.z, imagePlaneModule.columnCosines.x, imagePlaneModule.columnCosines.y, imagePlaneModule.columnCosines.z];
3153
2788
 
3154
2789
  // Get IOP from ref series, compute supported orientations:
3155
- const validOrientations = Segmentation_4X_getValidOrientations(ImageOrientationPatient);
2790
+ const validOrientations = getValidOrientations(ImageOrientationPatient);
3156
2791
  const sliceLength = multiframe.Columns * multiframe.Rows;
3157
- const segMetadata = Segmentation_4X_getSegmentMetadata(multiframe, SeriesInstanceUID);
2792
+ const segMetadata = getSegmentMetadata(multiframe, SeriesInstanceUID);
3158
2793
  const TransferSyntaxUID = multiframe._meta.TransferSyntaxUID.Value[0];
3159
2794
  let pixelData;
3160
2795
  let pixelDataChunks;
@@ -3169,7 +2804,7 @@ async function Segmentation_4X_generateToolState(referencedImageIds, arrayBuffer
3169
2804
  // Todo: need to test this with rle data
3170
2805
  pixelDataChunks = [pixelData];
3171
2806
  } else {
3172
- pixelDataChunks = Segmentation_4X_unpackPixelData(multiframe, {
2807
+ pixelDataChunks = unpackPixelData(multiframe, {
3173
2808
  maxBytesPerChunk
3174
2809
  });
3175
2810
  if (!pixelDataChunks) {
@@ -3528,9 +3163,9 @@ function checkSEGsOverlapping(pixelData, multiframe, imageIds, validOrientations
3528
3163
  frameSegmentsMapping.set(imageIdIndex, [frameSegment]);
3529
3164
  }
3530
3165
  }
3531
- for (let _ref2 of frameSegmentsMapping.entries()) {
3532
- var _ref3 = (0,slicedToArray/* ["default"] */.A)(_ref2, 2);
3533
- let role = _ref3[1];
3166
+ for (let _ref3 of frameSegmentsMapping.entries()) {
3167
+ var _ref4 = (0,slicedToArray/* ["default"] */.A)(_ref3, 2);
3168
+ let role = _ref4[1];
3534
3169
  let temp2DArray = new TypedArrayConstructor(sliceLength).fill(0);
3535
3170
  for (let i = 0; i < role.length; ++i) {
3536
3171
  const frameSegment = role[i];
@@ -3538,7 +3173,7 @@ function checkSEGsOverlapping(pixelData, multiframe, imageIds, validOrientations
3538
3173
  const ImageOrientationPatientI = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
3539
3174
  const view = readFromUnpackedChunks(pixelData, frameSegment * sliceLength, sliceLength);
3540
3175
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
3541
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3176
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3542
3177
  if (!alignedPixelDataI) {
3543
3178
  Segmentation_4X_cs3dLogger.warn('Individual SEG frames are out of plane with respect to the first SEG frame, this is not yet supported, skipping this frame.');
3544
3179
  continue;
@@ -3601,7 +3236,7 @@ function insertOverlappingPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray,
3601
3236
  // and the other portion is in another chunk
3602
3237
  const view = readFromUnpackedChunks(pixelData, i * sliceLength, sliceLength);
3603
3238
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
3604
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3239
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3605
3240
  if (!alignedPixelDataI) {
3606
3241
  throw new Error('Individual SEG frames are out of plane with respect to the first SEG frame. ' + 'This is not yet supported. Aborting segmentation loading.');
3607
3242
  }
@@ -3611,7 +3246,9 @@ function insertOverlappingPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray,
3611
3246
  continue;
3612
3247
  }
3613
3248
  const sourceImageMetadata = metadataProvider.get('instance', imageId);
3614
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
3249
+ // Compare the aligned frame: a frame rotated by 90 degrees in-plane has
3250
+ // its Rows and Columns swapped relative to the source image.
3251
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
3615
3252
  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. ');
3616
3253
  }
3617
3254
  const imageIdIndex = imageIds.findIndex(element => element === imageId);
@@ -3706,7 +3343,7 @@ function insertPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray, labelmapBu
3706
3343
  const ImageOrientationPatientI = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
3707
3344
  const view = readFromUnpackedChunks(pixelData, i * sliceLength, sliceLength);
3708
3345
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
3709
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3346
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
3710
3347
  if (!alignedPixelDataI) {
3711
3348
  throw new Error('Individual SEG frames are out of plane with respect to the first SEG frame. ' + 'This is not yet supported. Aborting segmentation loading.');
3712
3349
  }
@@ -3723,7 +3360,7 @@ function insertPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray, labelmapBu
3723
3360
  continue;
3724
3361
  }
3725
3362
  const sourceImageMetadata = imageIdMaps.metadata[imageId];
3726
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
3363
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
3727
3364
  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. ');
3728
3365
  }
3729
3366
  const imageIdIndex = imageIdMaps.indices[imageId];
@@ -3775,388 +3412,798 @@ function insertPixelDataPlanar(segmentsOnFrame, segmentsOnFrameArray, labelmapBu
3775
3412
  }
3776
3413
 
3777
3414
  /**
3778
- * unpackPixelData - Unpacks bit packed pixelData if the Segmentation is BINARY.
3415
+ * unpackPixelData - Unpacks bit packed pixelData if the Segmentation is BINARY.
3416
+ *
3417
+ * @param {Object} multiframe The multiframe dataset.
3418
+ * @param {Object} options Options for the unpacking.
3419
+ * @return {Uint8Array} The unpacked pixelData.
3420
+ */
3421
+ function unpackPixelData(multiframe, options) {
3422
+ const segType = multiframe.SegmentationType;
3423
+ let data;
3424
+ if (Array.isArray(multiframe.PixelData)) {
3425
+ data = multiframe.PixelData[0];
3426
+ } else {
3427
+ data = multiframe.PixelData;
3428
+ }
3429
+ if (data === undefined) {
3430
+ dcmjs_es/* .log.error */.Rm.error('This segmentation pixelData is undefined.');
3431
+ }
3432
+ if (segType === 'BINARY') {
3433
+ // For extreme big data, we can't unpack the data at once and we need to
3434
+ // chunk it and unpack each chunk separately.
3435
+ // MAX 2GB is the limit right now to allocate a buffer
3436
+ return getUnpackedChunks(data, options.maxBytesPerChunk);
3437
+ }
3438
+ if (segType === 'LABELMAP') {
3439
+ // For LABELMAP, we can return the data as is, since it is already in a
3440
+ // format that Cornerstone can handle. Also here we are returning the
3441
+ // whole data at once, since the storage is more efficent than BINARY mode
3442
+ if (multiframe.BitsStored === 8) {
3443
+ return new Uint8Array(data);
3444
+ } else if (multiframe.BitsStored === 16) {
3445
+ return new Uint16Array(data);
3446
+ } else {
3447
+ return new Uint8Array(data);
3448
+ }
3449
+ }
3450
+ const pixelData = new Uint8Array(data);
3451
+ const max = multiframe.MaximumFractionalValue;
3452
+ const onlyMaxAndZero = pixelData.find(element => element !== 0 && element !== max) === undefined;
3453
+ if (!onlyMaxAndZero) {
3454
+ // This is a fractional segmentation, which is not currently supported.
3455
+ return;
3456
+ }
3457
+ dcmjs_es/* .log.warn */.Rm.warn('This segmentation object is actually binary... processing as such.');
3458
+ return pixelData;
3459
+ }
3460
+ function getUnpackedChunks(data, maxBytesPerChunk) {
3461
+ var bitArray = new Uint8Array(data);
3462
+ var chunks = [];
3463
+ var maxBitsPerChunk = maxBytesPerChunk * 8;
3464
+ var numberOfChunks = Math.ceil(bitArray.length * 8 / maxBitsPerChunk);
3465
+ for (var i = 0; i < numberOfChunks; i++) {
3466
+ var startBit = i * maxBitsPerChunk;
3467
+ var endBit = Math.min(startBit + maxBitsPerChunk, bitArray.length * 8);
3468
+ var startByte = Math.floor(startBit / 8);
3469
+ var endByte = Math.ceil(endBit / 8);
3470
+ var chunk = bitArray.slice(startByte, endByte);
3471
+ var unpackedChunk = BitArray.unpack(chunk);
3472
+ chunks.push(unpackedChunk);
3473
+ }
3474
+ return chunks;
3475
+ }
3476
+
3477
+ /**
3478
+ * getImageIdOfSourceImageBySourceImageSequence - Returns the Cornerstone imageId of the source image.
3479
+ *
3480
+ * @param {Object} SourceImageSequence Sequence describing the source image.
3481
+ * @param {String[]} imageIds A list of imageIds.
3482
+ * @param {Object} sopUIDImageIdIndexMap A map of SOPInstanceUIDs to imageIds.
3483
+ * @return {String} The corresponding imageId.
3484
+ */
3485
+ function getImageIdOfSourceImageBySourceImageSequence(SourceImageSequence, sopUIDImageIdIndexMap) {
3486
+ const ReferencedSOPInstanceUID = SourceImageSequence.ReferencedSOPInstanceUID,
3487
+ ReferencedFrameNumber = SourceImageSequence.ReferencedFrameNumber;
3488
+ const baseImageId = sopUIDImageIdIndexMap[ReferencedSOPInstanceUID];
3489
+ if (!baseImageId) {
3490
+ Segmentation_4X_cs3dLogger.warn("No imageId found for SOPInstanceUID: ".concat(ReferencedSOPInstanceUID));
3491
+ return undefined;
3492
+ }
3493
+ if (ReferencedFrameNumber !== undefined) {
3494
+ if (baseImageId.includes('frames/')) {
3495
+ return baseImageId.replace(/frames\/\d+/, "frames/".concat(ReferencedFrameNumber));
3496
+ } else if (baseImageId.includes('dicomfile:')) {
3497
+ // dicomfile base 1, despite having frame=
3498
+ return baseImageId.replace(/frame=\d+/, "frame=".concat(ReferencedFrameNumber));
3499
+ } else if (baseImageId.includes('frame=') || baseImageId.includes('wadouri:')) {
3500
+ // OHIF local/wadouri use 1-based ?frame= / &frame= (same as dicomfile:).
3501
+ return baseImageId.replace(/frame=\d+/, "frame=".concat(ReferencedFrameNumber));
3502
+ } else {
3503
+ if (baseImageId.includes('wadors:')) {
3504
+ return "".concat(baseImageId, "/frames/").concat(ReferencedFrameNumber);
3505
+ } else {
3506
+ return "".concat(baseImageId, "?frame=").concat(ReferencedFrameNumber);
3507
+ }
3508
+ }
3509
+ }
3510
+ return baseImageId;
3511
+ }
3512
+
3513
+ /**
3514
+ * Determines if an image is a multiframe image based on its metadata.
3515
+ *
3516
+ * @param {Object} imageMetadata - The metadata object for the image
3517
+ * @param {number} [imageMetadata.NumberOfFrames] - The number of frames in the image
3518
+ * @returns {boolean} True if the image is a multiframe image (NumberOfFrames > 1)
3519
+ */
3520
+ function isMultiframeImage(imageMetadata) {
3521
+ return imageMetadata && imageMetadata.NumberOfFrames > 1;
3522
+ }
3523
+
3524
+ /**
3525
+ * getImageIdOfSourceImagebyGeometry - Returns the Cornerstone imageId of the source image.
3526
+ *
3527
+ * The lookup first matches the SEG frame position exactly with the source
3528
+ * image position. If no image matches, the lookup selects the source image
3529
+ * whose plane holds the SEG frame position. A SEG frame that is flipped or
3530
+ * rotated in-plane has its origin at a different corner of the source slice,
3531
+ * so only the plane match finds that frame.
3532
+ *
3533
+ * @param {String} ReferencedSeriesInstanceUID Referenced series of the source image.
3534
+ * @param {String} FrameOfReferenceUID Frame of reference.
3535
+ * @param {Object} PerFrameFunctionalGroup Sequence describing segmentation reference attributes per frame.
3536
+ * @param {String[]} imageIds A list of imageIds.
3537
+ * @param {Object} sopUIDImageIdIndexMap A map of SOPInstanceUIDs to imageIds.
3538
+ * @param {Float} tolerance The tolerance parameter
3539
+ *
3540
+ * @return {String} The corresponding imageId.
3541
+ */
3542
+ function getImageIdOfSourceImagebyGeometry(ReferencedSeriesInstanceUID, FrameOfReferenceUID, PerFrameFunctionalGroup, imageIds, metadataProvider, tolerance) {
3543
+ var _PerFrameFunctionalGr;
3544
+ if (!ReferencedSeriesInstanceUID || !((_PerFrameFunctionalGr = PerFrameFunctionalGroup.PlanePositionSequence) !== null && _PerFrameFunctionalGr !== void 0 && (_PerFrameFunctionalGr = _PerFrameFunctionalGr[0]) !== null && _PerFrameFunctionalGr !== void 0 && _PerFrameFunctionalGr.ImagePositionPatient)) {
3545
+ return undefined;
3546
+ }
3547
+ const segFramePosition = dist_esm/* .utilities.toNumber */.BF.Ro(PerFrameFunctionalGroup.PlanePositionSequence[0].ImagePositionPatient);
3548
+ const candidates = [];
3549
+ for (let imageId of imageIds) {
3550
+ const sourceImageMetadata = metadataProvider.get('instance', imageId);
3551
+ if (!sourceImageMetadata) {
3552
+ continue;
3553
+ }
3554
+ if (!sourceImageMetadata.ImagePositionPatient || sourceImageMetadata.FrameOfReferenceUID !== FrameOfReferenceUID || sourceImageMetadata.SeriesInstanceUID !== ReferencedSeriesInstanceUID) {
3555
+ continue;
3556
+ }
3557
+ const imagePlane = metadataProvider.get('imagePlaneModule', imageId);
3558
+ // For multiframe images, check each frame's position
3559
+ const position = dist_esm/* .utilities.toNumber */.BF.Ro(isMultiframeImage(sourceImageMetadata) ? imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.imagePositionPatient : sourceImageMetadata.ImagePositionPatient);
3560
+ if (!position) {
3561
+ continue;
3562
+ }
3563
+ if (esm.utilities.isEqual(segFramePosition, position, tolerance)) {
3564
+ return imageId;
3565
+ }
3566
+ candidates.push({
3567
+ imageId,
3568
+ position,
3569
+ imagePlane
3570
+ });
3571
+ }
3572
+ for (const _ref5 of candidates) {
3573
+ const imageId = _ref5.imageId;
3574
+ const position = _ref5.position;
3575
+ const imagePlane = _ref5.imagePlane;
3576
+ const rowCosines = dist_esm/* .utilities.toNumber */.BF.Ro(imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.rowCosines);
3577
+ const columnCosines = dist_esm/* .utilities.toNumber */.BF.Ro(imagePlane === null || imagePlane === void 0 ? void 0 : imagePlane.columnCosines);
3578
+ if (!rowCosines || !columnCosines) {
3579
+ continue;
3580
+ }
3581
+ const normal = gl_matrix_esm/* .vec3.cross */.eR.$A([0, 0, 0], rowCosines, columnCosines);
3582
+ const distance = esm.utilities.voxelSlab.signedDistanceToPlane(segFramePosition, position, normal);
3583
+ if (Math.abs(distance) < tolerance) {
3584
+ return imageId;
3585
+ }
3586
+ }
3587
+ return undefined;
3588
+ }
3589
+
3590
+ /**
3591
+ * getValidOrientations - returns the 8 in-plane orientations of a source
3592
+ * image, as the row (r) and column (c) cosines of a SEG frame in that plane.
3593
+ *
3594
+ * | Index | SEG IOP | SEG frame relative to the source |
3595
+ * | ----- | ---------- | -------------------------------- |
3596
+ * | 0 | (r, c) | identity |
3597
+ * | 1 | (r, -c) | flipped vertically |
3598
+ * | 2 | (-r, c) | flipped horizontally |
3599
+ * | 3 | (c, -r) | rotated 90 degrees |
3600
+ * | 4 | (c, r) | transposed |
3601
+ * | 5 | (-c, -r) | anti-transposed |
3602
+ * | 6 | (-r, -c) | rotated 180 degrees |
3603
+ * | 7 | (-c, r) | rotated 270 degrees |
3604
+ *
3605
+ * The list is built from the cosines directly: dcmjs
3606
+ * rotateDirectionCosinesInPlane negates its result, so it never yields the
3607
+ * 180 degree orientation. See
3608
+ * https://github.com/cornerstonejs/cornerstone3D/issues/2959
3609
+ *
3610
+ * @param {Number[6]|String[6]} iop The row (0..2) and column (3..5) direction
3611
+ * cosines. DS strings are converted to numbers.
3612
+ * @return {Number[8][6]} The valid orientations, in the order of the table.
3613
+ */
3614
+ function getValidOrientations(iop) {
3615
+ const numericIop = dist_esm/* .utilities.toNumber */.BF.Ro(iop);
3616
+ const r = numericIop.slice(0, 3);
3617
+ const c = numericIop.slice(3, 6);
3618
+ const negR = gl_matrix_esm/* .vec3.negate */.eR.ze([0, 0, 0], r);
3619
+ const negC = gl_matrix_esm/* .vec3.negate */.eR.ze([0, 0, 0], c);
3620
+ return [[...r, ...c], [...r, ...negC], [...negR, ...c], [...c, ...negR], [...c, ...r], [...negC, ...negR], [...negR, ...negC], [...negC, ...r]];
3621
+ }
3622
+
3623
+ /**
3624
+ * The pixel operation that aligns a SEG frame with its source image, per entry
3625
+ * of getValidOrientations. The aligned pixel (a, b) reads the SEG pixel (i, j),
3626
+ * where (i, j) is (a, b), or (b, a) when `transpose` is set, and then
3627
+ * `flipRows` and `flipColumns` mirror i and j.
3628
+ */
3629
+ const ORIENTATION_ALIGNMENTS = [{
3630
+ transpose: false,
3631
+ flipRows: false,
3632
+ flipColumns: false
3633
+ }, {
3634
+ transpose: false,
3635
+ flipRows: true,
3636
+ flipColumns: false
3637
+ }, {
3638
+ transpose: false,
3639
+ flipRows: false,
3640
+ flipColumns: true
3641
+ }, {
3642
+ transpose: true,
3643
+ flipRows: true,
3644
+ flipColumns: false
3645
+ }, {
3646
+ transpose: true,
3647
+ flipRows: false,
3648
+ flipColumns: false
3649
+ }, {
3650
+ transpose: true,
3651
+ flipRows: true,
3652
+ flipColumns: true
3653
+ }, {
3654
+ transpose: false,
3655
+ flipRows: true,
3656
+ flipColumns: true
3657
+ }, {
3658
+ transpose: true,
3659
+ flipRows: false,
3660
+ flipColumns: true
3661
+ }];
3662
+
3663
+ /**
3664
+ * alignPixelDataWithSourceData - finds the orientation of a SEG frame in the
3665
+ * list from getValidOrientations, and returns the frame in the pixel order of
3666
+ * the source image.
3667
+ *
3668
+ * The result keeps the typed array type of the input, so 16-bit LABELMAP
3669
+ * values are not truncated. A frame that is not aligned already is copied in
3670
+ * one pass.
3671
+ *
3672
+ * @param {Ndarray} pixelData2D - The SEG frame, with shape [Rows, Columns].
3673
+ * @param {Number[6]|String[6]} iop - The orientation of the SEG frame. DS
3674
+ * strings are converted to numbers.
3675
+ * @param {Number[8][6]} orientations - The result of getValidOrientations.
3676
+ * @param {Number} tolerance - The tolerance of the IOP comparison.
3677
+ * @return {Ndarray|undefined} The aligned frame, with shape
3678
+ * [source Rows, source Columns], or undefined when the frame is not in-plane.
3679
+ */
3680
+ function alignPixelDataWithSourceData(pixelData2D, iop, orientations, tolerance) {
3681
+ const numericIop = dist_esm/* .utilities.toNumber */.BF.Ro(iop);
3682
+ const index = orientations.findIndex(orientation => esm.utilities.isEqual(numericIop, orientation, tolerance));
3683
+ if (index === -1) {
3684
+ return undefined;
3685
+ }
3686
+ if (index === 0) {
3687
+ return pixelData2D;
3688
+ }
3689
+ const _ORIENTATION_ALIGNMEN = ORIENTATION_ALIGNMENTS[index],
3690
+ transpose = _ORIENTATION_ALIGNMEN.transpose,
3691
+ flipRows = _ORIENTATION_ALIGNMEN.flipRows,
3692
+ flipColumns = _ORIENTATION_ALIGNMEN.flipColumns;
3693
+ const _pixelData2D$shape = (0,slicedToArray/* ["default"] */.A)(pixelData2D.shape, 2),
3694
+ rows = _pixelData2D$shape[0],
3695
+ columns = _pixelData2D$shape[1];
3696
+ const alignedRows = transpose ? columns : rows;
3697
+ const alignedColumns = transpose ? rows : columns;
3698
+ const TypedArrayConstructor = pixelData2D.data.constructor;
3699
+ const aligned = ndarray(new TypedArrayConstructor(rows * columns), [alignedRows, alignedColumns]);
3700
+ for (let a = 0; a < alignedRows; a++) {
3701
+ for (let b = 0; b < alignedColumns; b++) {
3702
+ let i = transpose ? b : a;
3703
+ let j = transpose ? a : b;
3704
+ if (flipRows) {
3705
+ i = rows - 1 - i;
3706
+ }
3707
+ if (flipColumns) {
3708
+ j = columns - 1 - j;
3709
+ }
3710
+ aligned.set(a, b, pixelData2D.get(i, j));
3711
+ }
3712
+ }
3713
+ return aligned;
3714
+ }
3715
+ function getSegmentMetadata(multiframe, seriesInstanceUid) {
3716
+ const segmentSequence = multiframe.SegmentSequence;
3717
+ const data = [];
3718
+
3719
+ /**
3720
+ * Index segments by their SegmentNumber rather than array position.
3721
+ * This is required for LABELMAP segmentations where SegmentNumber may
3722
+ * start at 0 (for background) or have gaps. The DICOM standard only
3723
+ * requires SegmentNumber >= 1 for BINARY/FRACTIONAL types, but LABELMAP
3724
+ * allows more flexibility (see DICOM Part 3, Section C.8.20.2.4).
3725
+ */
3726
+ for (const segment of esm.utilities.asArray(segmentSequence)) {
3727
+ if ((segment === null || segment === void 0 ? void 0 : segment.SegmentNumber) >= 0) {
3728
+ data[segment.SegmentNumber] = segment;
3729
+ }
3730
+ }
3731
+ return {
3732
+ seriesInstanceUid,
3733
+ data
3734
+ };
3735
+ }
3736
+
3737
+ /**
3738
+ * Reads a range of SAMPLES (typed-array elements, not bytes) from an array of
3739
+ * typed-array chunks and aggregates them into a new typed array of the same
3740
+ * element type. Chunks may be Uint8Array (8-bit / packed binary) or
3741
+ * Uint16Array (16-bit labelmaps); offsets and lengths are in elements so the
3742
+ * same sample-indexed math works for both widths.
3743
+ *
3744
+ * @param {Uint8Array[]|Uint16Array[]} chunks - Typed-array chunks (all the same type).
3745
+ * @param {number} offset - The offset of the first sample to read.
3746
+ * @param {number} length - The number of samples to read.
3747
+ * @returns {Uint8Array|Uint16Array} A view/copy containing the requested samples.
3748
+ */
3749
+ function readFromUnpackedChunks(chunks, offset, length) {
3750
+ var _chunks$0$constructor, _chunks$, _TypedArray$BYTES_PER;
3751
+ const mapping = getUnpackedOffsetAndLength(chunks, offset, length);
3752
+ const TypedArray = (_chunks$0$constructor = (_chunks$ = chunks[0]) === null || _chunks$ === void 0 ? void 0 : _chunks$.constructor) !== null && _chunks$0$constructor !== void 0 ? _chunks$0$constructor : Uint8Array;
3753
+ const bytesPerElement = (_TypedArray$BYTES_PER = TypedArray.BYTES_PER_ELEMENT) !== null && _TypedArray$BYTES_PER !== void 0 ? _TypedArray$BYTES_PER : 1;
3754
+
3755
+ // Chunks are typically subarray views that share one backing ArrayBuffer, so
3756
+ // `chunk.buffer` is the whole buffer (byte 0 = chunk 0) while the computed
3757
+ // offsets are chunk-relative. Add each chunk's own byteOffset so a view into
3758
+ // chunk N reads chunk N's bytes and not chunk 0's; element offsets are scaled
3759
+ // by the chunk's element width so 16-bit chunks are not read as bytes.
3760
+ // If all the data is in one chunk, we can just slice that chunk
3761
+ if (mapping.start.chunkIndex === mapping.end.chunkIndex) {
3762
+ const chunk = chunks[mapping.start.chunkIndex];
3763
+ return new TypedArray(chunk.buffer, chunk.byteOffset + mapping.start.offset * bytesPerElement, length);
3764
+ } else {
3765
+ // If the data spans multiple chunks, we need to create a new typed array and copy the data from each chunk
3766
+ let result = new TypedArray(length);
3767
+ let resultOffset = 0;
3768
+ for (let i = mapping.start.chunkIndex; i <= mapping.end.chunkIndex; i++) {
3769
+ let start = i === mapping.start.chunkIndex ? mapping.start.offset : 0;
3770
+ let end = i === mapping.end.chunkIndex ? mapping.end.offset : chunks[i].length;
3771
+ result.set(new TypedArray(chunks[i].buffer, chunks[i].byteOffset + start * bytesPerElement, end - start), resultOffset);
3772
+ resultOffset += end - start;
3773
+ }
3774
+ return result;
3775
+ }
3776
+ }
3777
+ function getUnpackedOffsetAndLength(chunks, offset, length) {
3778
+ var totalBytes = chunks.reduce((total, chunk) => total + chunk.length, 0);
3779
+ if (offset < 0 || offset + length > totalBytes) {
3780
+ throw new Error('Offset and length out of bounds');
3781
+ }
3782
+ var startChunkIndex = 0;
3783
+ var startOffsetInChunk = offset;
3784
+ while (startOffsetInChunk >= chunks[startChunkIndex].length) {
3785
+ startOffsetInChunk -= chunks[startChunkIndex].length;
3786
+ startChunkIndex++;
3787
+ }
3788
+ var endChunkIndex = startChunkIndex;
3789
+ var endOffsetInChunk = startOffsetInChunk + length;
3790
+ while (endOffsetInChunk > chunks[endChunkIndex].length) {
3791
+ endOffsetInChunk -= chunks[endChunkIndex].length;
3792
+ endChunkIndex++;
3793
+ }
3794
+ return {
3795
+ start: {
3796
+ chunkIndex: startChunkIndex,
3797
+ offset: startOffsetInChunk
3798
+ },
3799
+ end: {
3800
+ chunkIndex: endChunkIndex,
3801
+ offset: endOffsetInChunk
3802
+ }
3803
+ };
3804
+ }
3805
+ function calculateCentroid(imageIdIndexBufferIndex, multiframe, metadataProvider, imageIds) {
3806
+ let xAcc = 0;
3807
+ let yAcc = 0;
3808
+ let zAcc = 0;
3809
+ let worldXAcc = 0;
3810
+ let worldYAcc = 0;
3811
+ let worldZAcc = 0;
3812
+ let count = 0;
3813
+ for (const _ref6 of Object.entries(imageIdIndexBufferIndex)) {
3814
+ var _ref7 = (0,slicedToArray/* ["default"] */.A)(_ref6, 2);
3815
+ const imageIdIndex = _ref7[0];
3816
+ const bufferIndices = _ref7[1];
3817
+ const z = Number(imageIdIndex);
3818
+ if (!bufferIndices || bufferIndices.length === 0) {
3819
+ continue;
3820
+ }
3821
+
3822
+ // Get metadata for this slice
3823
+ const imageId = imageIds[z];
3824
+ const imagePlaneModule = metadataProvider.get('imagePlaneModule', imageId);
3825
+ if (!imagePlaneModule) {
3826
+ Segmentation_4X_cs3dLogger.debug('Missing imagePlaneModule metadata for centroid calculation');
3827
+ continue;
3828
+ }
3829
+ const imagePositionPatient = imagePlaneModule.imagePositionPatient,
3830
+ rowCosines = imagePlaneModule.rowCosines,
3831
+ columnCosines = imagePlaneModule.columnCosines,
3832
+ rowPixelSpacing = imagePlaneModule.rowPixelSpacing,
3833
+ columnPixelSpacing = imagePlaneModule.columnPixelSpacing;
3834
+ for (const bufferIndex of bufferIndices) {
3835
+ const y = Math.floor(bufferIndex / multiframe.Rows);
3836
+ const x = bufferIndex % multiframe.Rows;
3837
+
3838
+ // Image coordinates
3839
+ xAcc += x;
3840
+ yAcc += y;
3841
+ zAcc += z;
3842
+
3843
+ // Calculate world coordinates
3844
+ // P(world) = P(image) * IOP * spacing + IPP
3845
+ const worldX = imagePositionPatient[0] + x * rowCosines[0] * columnPixelSpacing + y * columnCosines[0] * rowPixelSpacing;
3846
+ const worldY = imagePositionPatient[1] + x * rowCosines[1] * columnPixelSpacing + y * columnCosines[1] * rowPixelSpacing;
3847
+ const worldZ = imagePositionPatient[2] + x * rowCosines[2] * columnPixelSpacing + y * columnCosines[2] * rowPixelSpacing;
3848
+ worldXAcc += worldX;
3849
+ worldYAcc += worldY;
3850
+ worldZAcc += worldZ;
3851
+ count++;
3852
+ }
3853
+ }
3854
+ return {
3855
+ image: {
3856
+ x: Math.floor(xAcc / count),
3857
+ y: Math.floor(yAcc / count),
3858
+ z: Math.floor(zAcc / count)
3859
+ },
3860
+ world: {
3861
+ x: worldXAcc / count,
3862
+ y: worldYAcc / count,
3863
+ z: worldZAcc / count
3864
+ },
3865
+ count
3866
+ };
3867
+ }
3868
+ const Segmentation = {
3869
+ generateSegmentation,
3870
+ generateToolState,
3871
+ fillSegmentation
3872
+ };
3873
+
3874
+
3875
+
3876
+ ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone/Segmentation_3X.js
3877
+
3878
+
3879
+
3880
+
3881
+
3882
+
3883
+ const Segmentation_3X_cs3dLogger = esm.utilities.logger.adaptersLog.getLogger('Cornerstone.Segmentation_3X');
3884
+ const Segmentation_3X_datasetToBlob = dcmjs_es/* .utilities.datasetToBlob */.BF.datasetToBlob,
3885
+ Segmentation_3X_BitArray = dcmjs_es/* .utilities.BitArray */.BF.BitArray,
3886
+ Segmentation_3X_DicomMessage = dcmjs_es/* .utilities.DicomMessage */.BF.DicomMessage,
3887
+ Segmentation_3X_DicomMetaDictionary = dcmjs_es/* .utilities.DicomMetaDictionary */.BF.DicomMetaDictionary;
3888
+ const Segmentation_3X_Normalizer = dcmjs_es/* .normalizers.Normalizer */.z8.Normalizer;
3889
+ const Segmentation_3X_SegmentationDerivation = dcmjs_es/* .derivations.Segmentation */.h4.Segmentation;
3890
+ const Segmentation_3X_Segmentation = {
3891
+ generateSegmentation: Segmentation_3X_generateSegmentation,
3892
+ generateToolState: Segmentation_3X_generateToolState
3893
+ };
3894
+
3895
+ /**
3779
3896
  *
3780
- * @param {Object} multiframe The multiframe dataset.
3781
- * @param {Object} options Options for the unpacking.
3782
- * @return {Uint8Array} The unpacked pixelData.
3897
+ * @typedef {Object} BrushData
3898
+ * @property {Object} toolState - The cornerstoneTools global toolState.
3899
+ * @property {Object[]} segments - The cornerstoneTools segment metadata that corresponds to the
3900
+ * seriesInstanceUid.
3783
3901
  */
3784
- function Segmentation_4X_unpackPixelData(multiframe, options) {
3785
- const segType = multiframe.SegmentationType;
3786
- let data;
3787
- if (Array.isArray(multiframe.PixelData)) {
3788
- data = multiframe.PixelData[0];
3789
- } else {
3790
- data = multiframe.PixelData;
3902
+
3903
+ /**
3904
+ * generateSegmentation - Generates cornerstoneTools brush data, given a stack of
3905
+ * imageIds, images and the cornerstoneTools brushData.
3906
+ *
3907
+ * @param {object[]} images An array of the cornerstone image objects.
3908
+ * @param {BrushData} brushData and object containing the brushData.
3909
+ * @returns {type} description
3910
+ */
3911
+ function Segmentation_3X_generateSegmentation(images, brushData) {
3912
+ let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
3913
+ includeSliceSpacing: true
3914
+ };
3915
+ const toolState = brushData.toolState,
3916
+ segments = brushData.segments;
3917
+
3918
+ // Calculate the dimensions of the data cube.
3919
+ const image0 = images[0];
3920
+ const dims = {
3921
+ x: image0.columns,
3922
+ y: image0.rows,
3923
+ z: images.length
3924
+ };
3925
+ dims.xy = dims.x * dims.y;
3926
+ const numSegments = _getSegCount(seg, segments);
3927
+ if (!numSegments) {
3928
+ throw new Error('No segments to export!');
3791
3929
  }
3792
- if (data === undefined) {
3793
- dcmjs_es/* .log.error */.Rm.error('This segmentation pixelData is undefined.');
3930
+ const isMultiframe = image0.imageId.includes('?frame');
3931
+ const seg = Segmentation_3X_createSegFromImages(images, isMultiframe, options);
3932
+ const _getNumberOfFramesPer = _getNumberOfFramesPerSegment(toolState, images, segments),
3933
+ referencedFramesPerSegment = _getNumberOfFramesPer.referencedFramesPerSegment,
3934
+ segmentIndicies = _getNumberOfFramesPer.segmentIndicies;
3935
+ let NumberOfFrames = 0;
3936
+ for (let i = 0; i < referencedFramesPerSegment.length; i++) {
3937
+ NumberOfFrames += referencedFramesPerSegment[i].length;
3794
3938
  }
3795
- if (segType === 'BINARY') {
3796
- // For extreme big data, we can't unpack the data at once and we need to
3797
- // chunk it and unpack each chunk separately.
3798
- // MAX 2GB is the limit right now to allocate a buffer
3799
- return getUnpackedChunks(data, options.maxBytesPerChunk);
3939
+ seg.setNumberOfFrames(NumberOfFrames);
3940
+ for (let i = 0; i < segmentIndicies.length; i++) {
3941
+ const segmentIndex = segmentIndicies[i];
3942
+ const referencedFrameIndicies = referencedFramesPerSegment[i];
3943
+
3944
+ // Frame numbers start from 1.
3945
+ const referencedFrameNumbers = referencedFrameIndicies.map(element => {
3946
+ return element + 1;
3947
+ });
3948
+ const segment = segments[segmentIndex];
3949
+ seg.addSegment(segment, _extractCornerstoneToolsPixelData(segmentIndex, referencedFrameIndicies, toolState, images, dims), referencedFrameNumbers);
3800
3950
  }
3801
- if (segType === 'LABELMAP') {
3802
- // For LABELMAP, we can return the data as is, since it is already in a
3803
- // format that Cornerstone can handle. Also here we are returning the
3804
- // whole data at once, since the storage is more efficent than BINARY mode
3805
- if (multiframe.BitsStored === 8) {
3806
- return new Uint8Array(data);
3807
- } else if (multiframe.BitsStored === 16) {
3808
- return new Uint16Array(data);
3809
- } else {
3810
- return new Uint8Array(data);
3951
+ seg.bitPackPixelData();
3952
+ const segBlob = Segmentation_3X_datasetToBlob(seg.dataset);
3953
+ return segBlob;
3954
+ }
3955
+ function _extractCornerstoneToolsPixelData(segmentIndex, referencedFrames, toolState, images, dims) {
3956
+ const pixelData = new Uint8Array(dims.xy * referencedFrames.length);
3957
+ let pixelDataIndex = 0;
3958
+ for (let i = 0; i < referencedFrames.length; i++) {
3959
+ const frame = referencedFrames[i];
3960
+ const imageId = images[frame].imageId;
3961
+ const imageIdSpecificToolState = toolState[imageId];
3962
+ const brushPixelData = imageIdSpecificToolState.brush.data[segmentIndex].pixelData;
3963
+ for (let p = 0; p < brushPixelData.length; p++) {
3964
+ pixelData[pixelDataIndex] = brushPixelData[p];
3965
+ pixelDataIndex++;
3811
3966
  }
3812
3967
  }
3813
- const pixelData = new Uint8Array(data);
3814
- const max = multiframe.MaximumFractionalValue;
3815
- const onlyMaxAndZero = pixelData.find(element => element !== 0 && element !== max) === undefined;
3816
- if (!onlyMaxAndZero) {
3817
- // This is a fractional segmentation, which is not currently supported.
3818
- return;
3819
- }
3820
- dcmjs_es/* .log.warn */.Rm.warn('This segmentation object is actually binary... processing as such.');
3821
3968
  return pixelData;
3822
3969
  }
3823
- function getUnpackedChunks(data, maxBytesPerChunk) {
3824
- var bitArray = new Uint8Array(data);
3825
- var chunks = [];
3826
- var maxBitsPerChunk = maxBytesPerChunk * 8;
3827
- var numberOfChunks = Math.ceil(bitArray.length * 8 / maxBitsPerChunk);
3828
- for (var i = 0; i < numberOfChunks; i++) {
3829
- var startBit = i * maxBitsPerChunk;
3830
- var endBit = Math.min(startBit + maxBitsPerChunk, bitArray.length * 8);
3831
- var startByte = Math.floor(startBit / 8);
3832
- var endByte = Math.ceil(endBit / 8);
3833
- var chunk = bitArray.slice(startByte, endByte);
3834
- var unpackedChunk = Segmentation_4X_BitArray.unpack(chunk);
3835
- chunks.push(unpackedChunk);
3836
- }
3837
- return chunks;
3838
- }
3839
-
3840
- /**
3841
- * getImageIdOfSourceImageBySourceImageSequence - Returns the Cornerstone imageId of the source image.
3842
- *
3843
- * @param {Object} SourceImageSequence Sequence describing the source image.
3844
- * @param {String[]} imageIds A list of imageIds.
3845
- * @param {Object} sopUIDImageIdIndexMap A map of SOPInstanceUIDs to imageIds.
3846
- * @return {String} The corresponding imageId.
3847
- */
3848
- function getImageIdOfSourceImageBySourceImageSequence(SourceImageSequence, sopUIDImageIdIndexMap) {
3849
- const ReferencedSOPInstanceUID = SourceImageSequence.ReferencedSOPInstanceUID,
3850
- ReferencedFrameNumber = SourceImageSequence.ReferencedFrameNumber;
3851
- const baseImageId = sopUIDImageIdIndexMap[ReferencedSOPInstanceUID];
3852
- if (!baseImageId) {
3853
- Segmentation_4X_cs3dLogger.warn("No imageId found for SOPInstanceUID: ".concat(ReferencedSOPInstanceUID));
3854
- return undefined;
3970
+ function _getNumberOfFramesPerSegment(toolState, images, segments) {
3971
+ const segmentIndicies = [];
3972
+ const referencedFramesPerSegment = [];
3973
+ for (let i = 0; i < segments.length; i++) {
3974
+ if (segments[i]) {
3975
+ segmentIndicies.push(i);
3976
+ referencedFramesPerSegment.push([]);
3977
+ }
3855
3978
  }
3856
- if (ReferencedFrameNumber !== undefined) {
3857
- if (baseImageId.includes('frames/')) {
3858
- return baseImageId.replace(/frames\/\d+/, "frames/".concat(ReferencedFrameNumber));
3859
- } else if (baseImageId.includes('dicomfile:')) {
3860
- // dicomfile base 1, despite having frame=
3861
- return baseImageId.replace(/frame=\d+/, "frame=".concat(ReferencedFrameNumber));
3862
- } else if (baseImageId.includes('frame=') || baseImageId.includes('wadouri:')) {
3863
- // OHIF local/wadouri use 1-based ?frame= / &frame= (same as dicomfile:).
3864
- return baseImageId.replace(/frame=\d+/, "frame=".concat(ReferencedFrameNumber));
3865
- } else {
3866
- if (baseImageId.includes('wadors:')) {
3867
- return "".concat(baseImageId, "/frames/").concat(ReferencedFrameNumber);
3868
- } else {
3869
- return "".concat(baseImageId, "?frame=").concat(ReferencedFrameNumber);
3979
+ for (let z = 0; z < images.length; z++) {
3980
+ const imageId = images[z].imageId;
3981
+ const imageIdSpecificToolState = toolState[imageId];
3982
+ for (let i = 0; i < segmentIndicies.length; i++) {
3983
+ const segIdx = segmentIndicies[i];
3984
+ if (imageIdSpecificToolState && imageIdSpecificToolState.brush && imageIdSpecificToolState.brush.data && imageIdSpecificToolState.brush.data[segIdx] && imageIdSpecificToolState.brush.data[segIdx].pixelData) {
3985
+ referencedFramesPerSegment[i].push(z);
3870
3986
  }
3871
3987
  }
3872
3988
  }
3873
- return baseImageId;
3989
+ return {
3990
+ referencedFramesPerSegment,
3991
+ segmentIndicies
3992
+ };
3993
+ }
3994
+ function _getSegCount(seg, segments) {
3995
+ let numSegments = 0;
3996
+ for (let i = 0; i < segments.length; i++) {
3997
+ if (segments[i]) {
3998
+ numSegments++;
3999
+ }
4000
+ }
4001
+ return numSegments;
3874
4002
  }
3875
4003
 
3876
4004
  /**
3877
- * Determines if an image is a multiframe image based on its metadata.
4005
+ * _createSegFromImages - description
3878
4006
  *
3879
- * @param {Object} imageMetadata - The metadata object for the image
3880
- * @param {number} [imageMetadata.NumberOfFrames] - The number of frames in the image
3881
- * @returns {boolean} True if the image is a multiframe image (NumberOfFrames > 1)
4007
+ * @param {Object[]} images An array of the cornerstone image objects.
4008
+ * @param {Boolean} isMultiframe Whether the images are multiframe.
4009
+ * @returns {Object} The Seg derived dataSet.
3882
4010
  */
3883
- function isMultiframeImage(imageMetadata) {
3884
- return imageMetadata && imageMetadata.NumberOfFrames > 1;
4011
+ function Segmentation_3X_createSegFromImages(images, isMultiframe, options) {
4012
+ const multiframe = getDatasetsFromImages(images, isMultiframe);
4013
+ return new Segmentation_3X_SegmentationDerivation([multiframe], options);
3885
4014
  }
3886
4015
 
3887
4016
  /**
3888
- * getImageIdOfSourceImagebyGeometry - Returns the Cornerstone imageId of the source image.
3889
- *
3890
- * @param {String} ReferencedSeriesInstanceUID Referenced series of the source image.
3891
- * @param {String} FrameOfReferenceUID Frame of reference.
3892
- * @param {Object} PerFrameFunctionalGroup Sequence describing segmentation reference attributes per frame.
3893
- * @param {String[]} imageIds A list of imageIds.
3894
- * @param {Object} sopUIDImageIdIndexMap A map of SOPInstanceUIDs to imageIds.
3895
- * @param {Float} tolerance The tolerance parameter
4017
+ * generateToolState - Given a set of cornrstoneTools imageIds and a Segmentation buffer,
4018
+ * derive cornerstoneTools toolState and brush metadata.
3896
4019
  *
3897
- * @return {String} The corresponding imageId.
4020
+ * @param {string[]} imageIds An array of the imageIds.
4021
+ * @param {ArrayBuffer} arrayBuffer The SEG arrayBuffer.
4022
+ * @param {*} metadataProvider
4023
+ * @returns {Object} The toolState and an object from which the
4024
+ * segment metadata can be derived.
3898
4025
  */
3899
- function getImageIdOfSourceImagebyGeometry(ReferencedSeriesInstanceUID, FrameOfReferenceUID, PerFrameFunctionalGroup, imageIds, metadataProvider, tolerance) {
3900
- var _PerFrameFunctionalGr;
3901
- if (!ReferencedSeriesInstanceUID || !((_PerFrameFunctionalGr = PerFrameFunctionalGroup.PlanePositionSequence) !== null && _PerFrameFunctionalGr !== void 0 && (_PerFrameFunctionalGr = _PerFrameFunctionalGr[0]) !== null && _PerFrameFunctionalGr !== void 0 && _PerFrameFunctionalGr.ImagePositionPatient)) {
3902
- return undefined;
4026
+ function Segmentation_3X_generateToolState(imageIds, arrayBuffer, metadataProvider) {
4027
+ const dicomData = Segmentation_3X_DicomMessage.readFile(arrayBuffer);
4028
+ const dataset = Segmentation_3X_DicomMetaDictionary.naturalizeDataset(dicomData.dict);
4029
+ dataset._meta = Segmentation_3X_DicomMetaDictionary.namifyDataset(dicomData.meta);
4030
+ const multiframe = Segmentation_3X_Normalizer.normalizeToDataset([dataset]);
4031
+ const imagePlaneModule = metadataProvider.get('imagePlaneModule', imageIds[0]);
4032
+ if (!imagePlaneModule) {
4033
+ Segmentation_3X_cs3dLogger.warn('Insufficient metadata, imagePlaneModule missing.');
3903
4034
  }
3904
- const segFramePosition = PerFrameFunctionalGroup.PlanePositionSequence[0].ImagePositionPatient;
3905
- for (let imageId of imageIds) {
3906
- const sourceImageMetadata = metadataProvider.get('instance', imageId);
3907
- if (!sourceImageMetadata) {
3908
- continue;
3909
- }
3910
- const isMultiframe = isMultiframeImage(sourceImageMetadata);
3911
- if (!sourceImageMetadata.ImagePositionPatient || sourceImageMetadata.FrameOfReferenceUID !== FrameOfReferenceUID || sourceImageMetadata.SeriesInstanceUID !== ReferencedSeriesInstanceUID) {
3912
- continue;
3913
- }
4035
+ const ImageOrientationPatient = Array.isArray(imagePlaneModule.rowCosines) ? [...imagePlaneModule.rowCosines, ...imagePlaneModule.columnCosines] : [imagePlaneModule.rowCosines.x, imagePlaneModule.rowCosines.y, imagePlaneModule.rowCosines.z, imagePlaneModule.columnCosines.x, imagePlaneModule.columnCosines.y, imagePlaneModule.columnCosines.z];
3914
4036
 
3915
- // For multiframe images, check each frame's position
3916
- if (isMultiframe) {
3917
- var _metadataProvider$get2;
3918
- const framePosition = (_metadataProvider$get2 = metadataProvider.get('imagePlaneModule', imageId)) === null || _metadataProvider$get2 === void 0 ? void 0 : _metadataProvider$get2.imagePositionPatient;
3919
- if (framePosition && esm.utilities.isEqual(segFramePosition, framePosition, tolerance)) {
3920
- return imageId;
3921
- }
3922
- } else if (esm.utilities.isEqual(segFramePosition, sourceImageMetadata.ImagePositionPatient, tolerance)) {
3923
- return imageId;
4037
+ // Get IOP from ref series, compute supported orientations:
4038
+ const validOrientations = getValidOrientations(ImageOrientationPatient);
4039
+ const SharedFunctionalGroupsSequence = multiframe.SharedFunctionalGroupsSequence;
4040
+ const sharedImageOrientationPatient = SharedFunctionalGroupsSequence.PlaneOrientationSequence ? SharedFunctionalGroupsSequence.PlaneOrientationSequence.ImageOrientationPatient : undefined;
4041
+ const sliceLength = multiframe.Columns * multiframe.Rows;
4042
+ const segMetadata = Segmentation_3X_getSegmentMetadata(multiframe);
4043
+ const pixelData = Segmentation_3X_unpackPixelData(multiframe);
4044
+ const PerFrameFunctionalGroupsSequence = multiframe.PerFrameFunctionalGroupsSequence;
4045
+ const toolState = {};
4046
+ let inPlane = true;
4047
+ for (let i = 0; i < PerFrameFunctionalGroupsSequence.length; i++) {
4048
+ const PerFrameFunctionalGroups = PerFrameFunctionalGroupsSequence[i];
4049
+ const ImageOrientationPatientI = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
4050
+ const pixelDataI2D = ndarray(new Uint8Array(pixelData.buffer, i * sliceLength, sliceLength), [multiframe.Rows, multiframe.Columns]);
4051
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations);
4052
+ if (!alignedPixelDataI) {
4053
+ Segmentation_3X_cs3dLogger.warn("This segmentation object is not in-plane with the source data. Bailing out of IO. It'd be better to render this with vtkjs. ");
4054
+ inPlane = false;
4055
+ break;
4056
+ }
4057
+ const segmentIndex = PerFrameFunctionalGroups.SegmentIdentificationSequence.ReferencedSegmentNumber - 1;
4058
+ let SourceImageSequence;
4059
+ if (SharedFunctionalGroupsSequence.DerivationImageSequence && SharedFunctionalGroupsSequence.DerivationImageSequence.SourceImageSequence) {
4060
+ SourceImageSequence = SharedFunctionalGroupsSequence.DerivationImageSequence.SourceImageSequence[i];
4061
+ } else {
4062
+ SourceImageSequence = PerFrameFunctionalGroups.DerivationImageSequence.SourceImageSequence;
3924
4063
  }
4064
+ const imageId = getImageIdOfSourceImage(SourceImageSequence, imageIds, metadataProvider);
4065
+ addImageIdSpecificBrushToolState(toolState, imageId, segmentIndex, alignedPixelDataI);
3925
4066
  }
3926
- return undefined;
4067
+ if (!inPlane) {
4068
+ return;
4069
+ }
4070
+ return {
4071
+ toolState,
4072
+ segMetadata
4073
+ };
3927
4074
  }
3928
4075
 
3929
4076
  /**
3930
- * getValidOrientations - returns an array of valid orientations.
4077
+ * unpackPixelData - Unpacks bitpacked pixelData if the Segmentation is BINARY.
3931
4078
  *
3932
- * @param {Number[6]} iop The row (0..2) an column (3..5) direction cosines.
3933
- * @return {Number[8][6]} An array of valid orientations.
4079
+ * @param {Object} multiframe The multiframe dataset.
4080
+ * @return {Uint8Array} The unpacked pixelData.
3934
4081
  */
3935
- function Segmentation_4X_getValidOrientations(iop) {
3936
- const orientations = [];
3937
-
3938
- // [0, 1, 2]: 0, 0hf, 0vf
3939
- // [3, 4, 5]: 90, 90hf, 90vf
3940
- // [6, 7]: 180, 270
3941
-
3942
- orientations[0] = iop;
3943
- orientations[1] = Segmentation_4X_flipIOP.h(iop);
3944
- orientations[2] = Segmentation_4X_flipIOP.v(iop);
3945
- const iop90 = Segmentation_4X_rotateDirectionCosinesInPlane(iop, Math.PI / 2);
3946
- orientations[3] = iop90;
3947
- orientations[4] = Segmentation_4X_flipIOP.h(iop90);
3948
- orientations[5] = Segmentation_4X_flipIOP.v(iop90);
3949
- orientations[6] = Segmentation_4X_rotateDirectionCosinesInPlane(iop, Math.PI);
3950
- orientations[7] = Segmentation_4X_rotateDirectionCosinesInPlane(iop, 1.5 * Math.PI);
3951
- return orientations;
4082
+ function Segmentation_3X_unpackPixelData(multiframe) {
4083
+ const segType = multiframe.SegmentationType;
4084
+ if (segType === 'BINARY') {
4085
+ return Segmentation_3X_BitArray.unpack(multiframe.PixelData);
4086
+ }
4087
+ const pixelData = new Uint8Array(multiframe.PixelData);
4088
+ const max = multiframe.MaximumFractionalValue;
4089
+ const onlyMaxAndZero = pixelData.find(element => element !== 0 && element !== max) === undefined;
4090
+ if (!onlyMaxAndZero) {
4091
+ dcmjs_es/* .log.warn */.Rm.warn('This is a fractional segmentation, which is not currently supported.');
4092
+ return;
4093
+ }
4094
+ dcmjs_es/* .log.warn */.Rm.warn('This segmentation object is actually binary... processing as such.');
4095
+ return pixelData;
3952
4096
  }
3953
4097
 
3954
4098
  /**
3955
- * alignPixelDataWithSourceData -
4099
+ * addImageIdSpecificBrushToolState - Adds brush pixel data to cornerstoneTools
4100
+ * formatted toolState object.
3956
4101
  *
3957
- * @param {Ndarray} pixelData2D - The data to align.
3958
- * @param {Number[6]} iop - The orientation of the image slice.
3959
- * @param {Number[8][6]} orientations - An array of valid imageOrientationPatient values.
3960
- * @param {Number} tolerance.
3961
- * @return {Ndarray} The aligned pixelData.
4102
+ * @param {Object} toolState The toolState object to modify
4103
+ * @param {String} imageId The imageId of the toolState to add the data.
4104
+ * @param {Number} segmentIndex The index of the segment data being added.
4105
+ * @param {Ndarray} pixelData2D The pixelData in Ndarry 2D format.
3962
4106
  */
3963
- function Segmentation_4X_alignPixelDataWithSourceData(pixelData2D, iop, orientations, tolerance) {
3964
- if (esm.utilities.isEqual(iop, orientations[0], tolerance)) {
3965
- return pixelData2D;
3966
- } else if (esm.utilities.isEqual(iop, orientations[1], tolerance)) {
3967
- // Flipped vertically.
3968
-
3969
- // Undo Flip
3970
- return Segmentation_4X_flipMatrix2D.v(pixelData2D);
3971
- } else if (esm.utilities.isEqual(iop, orientations[2], tolerance)) {
3972
- // Flipped horizontally.
3973
-
3974
- // Unfo flip
3975
- return Segmentation_4X_flipMatrix2D.h(pixelData2D);
3976
- } else if (esm.utilities.isEqual(iop, orientations[3], tolerance)) {
3977
- //Rotated 90 degrees
3978
-
3979
- // Rotate back
3980
- return Segmentation_4X_rotateMatrix902D(pixelData2D);
3981
- } else if (esm.utilities.isEqual(iop, orientations[4], tolerance)) {
3982
- //Rotated 90 degrees and fliped horizontally.
3983
-
3984
- // Undo flip and rotate back.
3985
- return Segmentation_4X_rotateMatrix902D(Segmentation_4X_flipMatrix2D.h(pixelData2D));
3986
- } else if (esm.utilities.isEqual(iop, orientations[5], tolerance)) {
3987
- // Rotated 90 degrees and fliped vertically
3988
-
3989
- // Unfo flip and rotate back.
3990
- return Segmentation_4X_rotateMatrix902D(Segmentation_4X_flipMatrix2D.v(pixelData2D));
3991
- } else if (esm.utilities.isEqual(iop, orientations[6], tolerance)) {
3992
- // Rotated 180 degrees. // TODO -> Do this more effeciently, there is a 1:1 mapping like 90 degree rotation.
3993
-
3994
- return Segmentation_4X_rotateMatrix902D(Segmentation_4X_rotateMatrix902D(pixelData2D));
3995
- } else if (esm.utilities.isEqual(iop, orientations[7], tolerance)) {
3996
- // Rotated 270 degrees
3997
-
3998
- // Rotate back.
3999
- return Segmentation_4X_rotateMatrix902D(Segmentation_4X_rotateMatrix902D(Segmentation_4X_rotateMatrix902D(pixelData2D)));
4107
+ function addImageIdSpecificBrushToolState(toolState, imageId, segmentIndex, pixelData2D) {
4108
+ if (!toolState[imageId]) {
4109
+ toolState[imageId] = {};
4110
+ toolState[imageId].brush = {};
4111
+ toolState[imageId].brush.data = [];
4112
+ } else if (!toolState[imageId].brush) {
4113
+ toolState[imageId].brush = {};
4114
+ toolState[imageId].brush.data = [];
4115
+ } else if (!toolState[imageId].brush.data) {
4116
+ toolState[imageId].brush.data = [];
4000
4117
  }
4001
- }
4002
- function Segmentation_4X_getSegmentMetadata(multiframe, seriesInstanceUid) {
4003
- const segmentSequence = multiframe.SegmentSequence;
4004
- const data = [];
4005
-
4006
- /**
4007
- * Index segments by their SegmentNumber rather than array position.
4008
- * This is required for LABELMAP segmentations where SegmentNumber may
4009
- * start at 0 (for background) or have gaps. The DICOM standard only
4010
- * requires SegmentNumber >= 1 for BINARY/FRACTIONAL types, but LABELMAP
4011
- * allows more flexibility (see DICOM Part 3, Section C.8.20.2.4).
4012
- */
4013
- for (const segment of esm.utilities.asArray(segmentSequence)) {
4014
- if ((segment === null || segment === void 0 ? void 0 : segment.SegmentNumber) >= 0) {
4015
- data[segment.SegmentNumber] = segment;
4118
+ toolState[imageId].brush.data[segmentIndex] = {};
4119
+ const brushDataI = toolState[imageId].brush.data[segmentIndex];
4120
+ brushDataI.pixelData = new Uint8Array(pixelData2D.data.length);
4121
+ const cToolsPixelData = brushDataI.pixelData;
4122
+ for (let p = 0; p < cToolsPixelData.length; p++) {
4123
+ if (pixelData2D.data[p]) {
4124
+ cToolsPixelData[p] = 1;
4125
+ } else {
4126
+ cToolsPixelData[p] = 0;
4016
4127
  }
4017
4128
  }
4018
- return {
4019
- seriesInstanceUid,
4020
- data
4021
- };
4022
4129
  }
4023
4130
 
4024
4131
  /**
4025
- * Reads a range of SAMPLES (typed-array elements, not bytes) from an array of
4026
- * typed-array chunks and aggregates them into a new typed array of the same
4027
- * element type. Chunks may be Uint8Array (8-bit / packed binary) or
4028
- * Uint16Array (16-bit labelmaps); offsets and lengths are in elements so the
4029
- * same sample-indexed math works for both widths.
4132
+ * getImageIdOfSourceImage - Returns the Cornerstone imageId of the source image.
4030
4133
  *
4031
- * @param {Uint8Array[]|Uint16Array[]} chunks - Typed-array chunks (all the same type).
4032
- * @param {number} offset - The offset of the first sample to read.
4033
- * @param {number} length - The number of samples to read.
4034
- * @returns {Uint8Array|Uint16Array} A view/copy containing the requested samples.
4134
+ * @param {Object} SourceImageSequence Sequence describing the source image.
4135
+ * @param {String[]} imageIds A list of imageIds.
4136
+ * @param {Object} metadataProvider A Cornerstone metadataProvider to query
4137
+ * metadata from imageIds.
4138
+ * @return {String} The corresponding imageId.
4035
4139
  */
4036
- function readFromUnpackedChunks(chunks, offset, length) {
4037
- var _chunks$0$constructor, _chunks$, _TypedArray$BYTES_PER;
4038
- const mapping = getUnpackedOffsetAndLength(chunks, offset, length);
4039
- const TypedArray = (_chunks$0$constructor = (_chunks$ = chunks[0]) === null || _chunks$ === void 0 ? void 0 : _chunks$.constructor) !== null && _chunks$0$constructor !== void 0 ? _chunks$0$constructor : Uint8Array;
4040
- const bytesPerElement = (_TypedArray$BYTES_PER = TypedArray.BYTES_PER_ELEMENT) !== null && _TypedArray$BYTES_PER !== void 0 ? _TypedArray$BYTES_PER : 1;
4041
-
4042
- // Chunks are typically subarray views that share one backing ArrayBuffer, so
4043
- // `chunk.buffer` is the whole buffer (byte 0 = chunk 0) while the computed
4044
- // offsets are chunk-relative. Add each chunk's own byteOffset so a view into
4045
- // chunk N reads chunk N's bytes and not chunk 0's; element offsets are scaled
4046
- // by the chunk's element width so 16-bit chunks are not read as bytes.
4047
- // If all the data is in one chunk, we can just slice that chunk
4048
- if (mapping.start.chunkIndex === mapping.end.chunkIndex) {
4049
- const chunk = chunks[mapping.start.chunkIndex];
4050
- return new TypedArray(chunk.buffer, chunk.byteOffset + mapping.start.offset * bytesPerElement, length);
4051
- } else {
4052
- // If the data spans multiple chunks, we need to create a new typed array and copy the data from each chunk
4053
- let result = new TypedArray(length);
4054
- let resultOffset = 0;
4055
- for (let i = mapping.start.chunkIndex; i <= mapping.end.chunkIndex; i++) {
4056
- let start = i === mapping.start.chunkIndex ? mapping.start.offset : 0;
4057
- let end = i === mapping.end.chunkIndex ? mapping.end.offset : chunks[i].length;
4058
- result.set(new TypedArray(chunks[i].buffer, chunks[i].byteOffset + start * bytesPerElement, end - start), resultOffset);
4059
- resultOffset += end - start;
4060
- }
4061
- return result;
4062
- }
4140
+ function getImageIdOfSourceImage(SourceImageSequence, imageIds, metadataProvider) {
4141
+ const ReferencedSOPInstanceUID = SourceImageSequence.ReferencedSOPInstanceUID,
4142
+ ReferencedFrameNumber = SourceImageSequence.ReferencedFrameNumber;
4143
+ return ReferencedFrameNumber ? getImageIdOfReferencedFrame(ReferencedSOPInstanceUID, ReferencedFrameNumber, imageIds, metadataProvider) : getImageIdOfReferencedSingleFramedSOPInstance(ReferencedSOPInstanceUID, imageIds, metadataProvider);
4063
4144
  }
4064
- function getUnpackedOffsetAndLength(chunks, offset, length) {
4065
- var totalBytes = chunks.reduce((total, chunk) => total + chunk.length, 0);
4066
- if (offset < 0 || offset + length > totalBytes) {
4067
- throw new Error('Offset and length out of bounds');
4068
- }
4069
- var startChunkIndex = 0;
4070
- var startOffsetInChunk = offset;
4071
- while (startOffsetInChunk >= chunks[startChunkIndex].length) {
4072
- startOffsetInChunk -= chunks[startChunkIndex].length;
4073
- startChunkIndex++;
4074
- }
4075
- var endChunkIndex = startChunkIndex;
4076
- var endOffsetInChunk = startOffsetInChunk + length;
4077
- while (endOffsetInChunk > chunks[endChunkIndex].length) {
4078
- endOffsetInChunk -= chunks[endChunkIndex].length;
4079
- endChunkIndex++;
4080
- }
4081
- return {
4082
- start: {
4083
- chunkIndex: startChunkIndex,
4084
- offset: startOffsetInChunk
4085
- },
4086
- end: {
4087
- chunkIndex: endChunkIndex,
4088
- offset: endOffsetInChunk
4145
+
4146
+ /**
4147
+ * getImageIdOfReferencedSingleFramedSOPInstance - Returns the imageId
4148
+ * corresponding to the specified sopInstanceUid for single-frame images.
4149
+ *
4150
+ * @param {String} sopInstanceUid The sopInstanceUid of the desired image.
4151
+ * @param {String[]} imageIds The list of imageIds.
4152
+ * @param {Object} metadataProvider The metadataProvider to obtain sopInstanceUids
4153
+ * from the cornerstone imageIds.
4154
+ * @return {String} The imageId that corresponds to the sopInstanceUid.
4155
+ */
4156
+ function getImageIdOfReferencedSingleFramedSOPInstance(sopInstanceUid, imageIds, metadataProvider) {
4157
+ return imageIds.find(imageId => {
4158
+ const sopCommonModule = metadataProvider.get('sopCommonModule', imageId);
4159
+ if (!sopCommonModule) {
4160
+ return;
4089
4161
  }
4090
- };
4162
+ return sopCommonModule.sopInstanceUID === sopInstanceUid;
4163
+ });
4091
4164
  }
4092
- function calculateCentroid(imageIdIndexBufferIndex, multiframe, metadataProvider, imageIds) {
4093
- let xAcc = 0;
4094
- let yAcc = 0;
4095
- let zAcc = 0;
4096
- let worldXAcc = 0;
4097
- let worldYAcc = 0;
4098
- let worldZAcc = 0;
4099
- let count = 0;
4100
- for (const _ref4 of Object.entries(imageIdIndexBufferIndex)) {
4101
- var _ref5 = (0,slicedToArray/* ["default"] */.A)(_ref4, 2);
4102
- const imageIdIndex = _ref5[0];
4103
- const bufferIndices = _ref5[1];
4104
- const z = Number(imageIdIndex);
4105
- if (!bufferIndices || bufferIndices.length === 0) {
4106
- continue;
4107
- }
4108
4165
 
4109
- // Get metadata for this slice
4110
- const imageId = imageIds[z];
4111
- const imagePlaneModule = metadataProvider.get('imagePlaneModule', imageId);
4112
- if (!imagePlaneModule) {
4113
- Segmentation_4X_cs3dLogger.debug('Missing imagePlaneModule metadata for centroid calculation');
4114
- continue;
4166
+ /**
4167
+ * getImageIdOfReferencedFrame - Returns the imageId corresponding to the
4168
+ * specified sopInstanceUid and frameNumber for multi-frame images.
4169
+ *
4170
+ * @param {String} sopInstanceUid The sopInstanceUid of the desired image.
4171
+ * @param {Number} frameNumber The frame number.
4172
+ * @param {String} imageIds The list of imageIds.
4173
+ * @param {Object} metadataProvider The metadataProvider to obtain sopInstanceUids
4174
+ * from the cornerstone imageIds.
4175
+ * @return {String} The imageId that corresponds to the sopInstanceUid.
4176
+ */
4177
+ function getImageIdOfReferencedFrame(sopInstanceUid, frameNumber, imageIds, metadataProvider) {
4178
+ const imageId = imageIds.find(imageId => {
4179
+ const sopCommonModule = metadataProvider.get('sopCommonModule', imageId);
4180
+ if (!sopCommonModule) {
4181
+ return;
4115
4182
  }
4116
- const imagePositionPatient = imagePlaneModule.imagePositionPatient,
4117
- rowCosines = imagePlaneModule.rowCosines,
4118
- columnCosines = imagePlaneModule.columnCosines,
4119
- rowPixelSpacing = imagePlaneModule.rowPixelSpacing,
4120
- columnPixelSpacing = imagePlaneModule.columnPixelSpacing;
4121
- for (const bufferIndex of bufferIndices) {
4122
- const y = Math.floor(bufferIndex / multiframe.Rows);
4123
- const x = bufferIndex % multiframe.Rows;
4124
-
4125
- // Image coordinates
4126
- xAcc += x;
4127
- yAcc += y;
4128
- zAcc += z;
4129
-
4130
- // Calculate world coordinates
4131
- // P(world) = P(image) * IOP * spacing + IPP
4132
- const worldX = imagePositionPatient[0] + x * rowCosines[0] * columnPixelSpacing + y * columnCosines[0] * rowPixelSpacing;
4133
- const worldY = imagePositionPatient[1] + x * rowCosines[1] * columnPixelSpacing + y * columnCosines[1] * rowPixelSpacing;
4134
- const worldZ = imagePositionPatient[2] + x * rowCosines[2] * columnPixelSpacing + y * columnCosines[2] * rowPixelSpacing;
4135
- worldXAcc += worldX;
4136
- worldYAcc += worldY;
4137
- worldZAcc += worldZ;
4138
- count++;
4183
+ const imageIdFrameNumber = Number(imageId.split('frame=')[1]);
4184
+ return (
4185
+ //frameNumber is zero indexed for cornerstoneDICOMImageLoader image Ids.
4186
+ sopCommonModule.sopInstanceUID === sopInstanceUid && imageIdFrameNumber === frameNumber - 1
4187
+ );
4188
+ });
4189
+ return imageId;
4190
+ }
4191
+ function Segmentation_3X_getSegmentMetadata(multiframe) {
4192
+ const data = [];
4193
+ const segmentSequence = multiframe.SegmentSequence;
4194
+ if (Array.isArray(segmentSequence)) {
4195
+ for (let segIdx = 0; segIdx < segmentSequence.length; segIdx++) {
4196
+ data.push(segmentSequence[segIdx]);
4139
4197
  }
4198
+ } else {
4199
+ // Only one segment, will be stored as an object.
4200
+ data.push(segmentSequence);
4140
4201
  }
4141
4202
  return {
4142
- image: {
4143
- x: Math.floor(xAcc / count),
4144
- y: Math.floor(yAcc / count),
4145
- z: Math.floor(zAcc / count)
4146
- },
4147
- world: {
4148
- x: worldXAcc / count,
4149
- y: worldYAcc / count,
4150
- z: worldZAcc / count
4151
- },
4152
- count
4203
+ seriesInstanceUid: multiframe.ReferencedSeriesSequence.SeriesInstanceUID,
4204
+ data
4153
4205
  };
4154
4206
  }
4155
- const Segmentation_4X_Segmentation = {
4156
- generateSegmentation: Segmentation_4X_generateSegmentation,
4157
- generateToolState: Segmentation_4X_generateToolState,
4158
- fillSegmentation
4159
- };
4160
4207
 
4161
4208
 
4162
4209
 
@@ -4182,10 +4229,10 @@ function Segmentation_generateSegmentation(images, labelmaps3DorBrushData) {
4182
4229
  };
4183
4230
  let cornerstoneToolsVersion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 4;
4184
4231
  if (cornerstoneToolsVersion === 4) {
4185
- return Segmentation_4X_Segmentation.generateSegmentation(images, labelmaps3DorBrushData, options);
4232
+ return Segmentation.generateSegmentation(images, labelmaps3DorBrushData, options);
4186
4233
  }
4187
4234
  if (cornerstoneToolsVersion === 3) {
4188
- return Segmentation.generateSegmentation(images, labelmaps3DorBrushData, options);
4235
+ return Segmentation_3X_Segmentation.generateSegmentation(images, labelmaps3DorBrushData, options);
4189
4236
  }
4190
4237
  Segmentation_cs3dLogger.warn("No generateSegmentation adapter for cornerstone version ".concat(cornerstoneToolsVersion, ", exiting."));
4191
4238
  }
@@ -4209,10 +4256,10 @@ function Segmentation_generateToolState(imageIds, arrayBuffer, metadataProvider)
4209
4256
  let tolerance = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1e-3;
4210
4257
  let cornerstoneToolsVersion = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 4;
4211
4258
  if (cornerstoneToolsVersion === 4) {
4212
- return Segmentation_4X_Segmentation.generateToolState(imageIds, arrayBuffer, metadataProvider, skipOverlapping, tolerance);
4259
+ return Segmentation.generateToolState(imageIds, arrayBuffer, metadataProvider, skipOverlapping, tolerance);
4213
4260
  }
4214
4261
  if (cornerstoneToolsVersion === 3) {
4215
- return Segmentation.generateToolState(imageIds, arrayBuffer, metadataProvider);
4262
+ return Segmentation_3X_Segmentation.generateToolState(imageIds, arrayBuffer, metadataProvider);
4216
4263
  }
4217
4264
  Segmentation_cs3dLogger.warn("No generateToolState adapter for cornerstone version ".concat(cornerstoneToolsVersion, ", exiting."));
4218
4265
  }
@@ -4231,7 +4278,7 @@ function Segmentation_fillSegmentation(segmentation, inputLabelmaps3D) {
4231
4278
  };
4232
4279
  let cornerstoneToolsVersion = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 4;
4233
4280
  if (cornerstoneToolsVersion === 4) {
4234
- return Segmentation_4X_Segmentation.fillSegmentation(segmentation, inputLabelmaps3D, options);
4281
+ return Segmentation.fillSegmentation(segmentation, inputLabelmaps3D, options);
4235
4282
  }
4236
4283
  Segmentation_cs3dLogger.warn("No generateSegmentation adapter for cornerstone version ".concat(cornerstoneToolsVersion, ", exiting."));
4237
4284
  }
@@ -6234,8 +6281,6 @@ _Length = Length_Length;
6234
6281
 
6235
6282
 
6236
6283
 
6237
- // EXTERNAL MODULE: ../../node_modules/gl-matrix/esm/index.js
6238
- var gl_matrix_esm = __webpack_require__(50341);
6239
6284
  ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/ControlPointPolyline.js
6240
6285
 
6241
6286
 
@@ -6674,8 +6719,9 @@ function maxSegmentValue(labelmap3DArray, frameIndices) {
6674
6719
  return;
6675
6720
  }
6676
6721
  for (let i = 0; i < pixelData.length; i++) {
6677
- if (pixelData[i] > max) {
6678
- max = pixelData[i];
6722
+ const segmentIndex = pixelData[i] ? getSegmentIndexForLabel(labelmap3D, pixelData[i]) : 0;
6723
+ if (segmentIndex > max) {
6724
+ max = segmentIndex;
6679
6725
  }
6680
6726
  }
6681
6727
  });
@@ -6761,10 +6807,10 @@ function fillLabelmapSegmentation(segmentation, inputLabelmaps3D, metadata, imag
6761
6807
  }
6762
6808
  const len = Math.min(source.length, frameLength);
6763
6809
  for (let i = 0; i < len; i++) {
6764
- const value = source[i];
6765
- if (value === 0) {
6810
+ if (source[i] === 0) {
6766
6811
  continue;
6767
6812
  }
6813
+ const value = getSegmentIndexForLabel(labelmap3D, source[i]);
6768
6814
  if (frame[i] !== 0 && frame[i] !== value && !overlapWarned) {
6769
6815
  generateSegmentation_cs3dLogger.warn('generateSegmentation: overlapping labelmap segments detected on the ' + 'same voxel while exporting a LABELMAP SEG; the later labelmap wins.');
6770
6816
  overlapWarned = true;
@@ -6899,6 +6945,7 @@ function _createMultiframeSegmentationFromReferencedImages(images, metadata, opt
6899
6945
  const seriesData = metadata.get(generateSegmentation_MetadataModules.SERIES_DATA, imageId);
6900
6946
  const imageData = metadata.get(generateSegmentation_MetadataModules.IMAGE_DATA, imageId);
6901
6947
  return generateSegmentation_objectSpread(generateSegmentation_objectSpread(generateSegmentation_objectSpread(generateSegmentation_objectSpread({}, studyData), seriesData), imageData), {}, {
6948
+ NumberOfFrames: 1,
6902
6949
  PixelData: image.voxelManager.getScalarData(),
6903
6950
  BitsAllocated: 16,
6904
6951
  _vrMap: {
@@ -6973,7 +7020,7 @@ function generateLabelMaps2DFrom3D(labelmap3D) {
6973
7020
 
6974
7021
 
6975
7022
  // EXTERNAL MODULE: ../../node_modules/@cornerstonejs/tools/dist/esm/index.js
6976
- var dist_esm = __webpack_require__(17819);
7023
+ var tools_dist_esm = __webpack_require__(17819);
6977
7024
  ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/adapters/Cornerstone3D/Segmentation/compactMergeSegData.js
6978
7025
  const checkHasOverlapping = _ref => {
6979
7026
  let largerArray = _ref.largerArray,
@@ -7477,8 +7524,8 @@ async function createLabelmapsFromSegImageIds(referencedImageIds, segImageId, me
7477
7524
  labelmapImagesFromBuffer_cs3dLogger.warn('Insufficient metadata, imagePlaneModule missing.');
7478
7525
  }
7479
7526
  const ImageOrientationPatient = Array.isArray(imagePlaneModule.rowCosines) ? [...imagePlaneModule.rowCosines, ...imagePlaneModule.columnCosines] : [imagePlaneModule.rowCosines.x, imagePlaneModule.rowCosines.y, imagePlaneModule.rowCosines.z, imagePlaneModule.columnCosines.x, imagePlaneModule.columnCosines.y, imagePlaneModule.columnCosines.z];
7480
- const validOrientations = Segmentation_4X_getValidOrientations(ImageOrientationPatient);
7481
- const segMetadata = Segmentation_4X_getSegmentMetadata(multiframe, SeriesInstanceUID);
7527
+ const validOrientations = getValidOrientations(ImageOrientationPatient);
7528
+ const segMetadata = getSegmentMetadata(multiframe, SeriesInstanceUID);
7482
7529
  const _await$decodeSegPixel = await decodeSegPixelDataFromFrameIds({
7483
7530
  segImageId,
7484
7531
  multiframe,
@@ -7566,7 +7613,7 @@ async function createLabelmapsFromSegImageIds(referencedImageIds, segImageId, me
7566
7613
  overlappingSegments: hasOverlappingSegments
7567
7614
  };
7568
7615
  }
7569
- const throttledTriggerLoadProgressEvent = dist_esm.utilities.throttle(percentComplete => {
7616
+ const throttledTriggerLoadProgressEvent = tools_dist_esm.utilities.throttle(percentComplete => {
7570
7617
  (0,esm.triggerEvent)(esm.eventTarget, Events_Events.SEGMENTATION_LOAD_PROGRESS, {
7571
7618
  percentComplete
7572
7619
  });
@@ -7608,7 +7655,7 @@ function labelmapImagesFromBuffer_insertPixelDataPlanar(_ref0) {
7608
7655
  }
7609
7656
  const view = readFromUnpackedChunks(pixelDataChunks, i * sliceLength, sliceLength);
7610
7657
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
7611
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7658
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7612
7659
  if (!alignedPixelDataI) {
7613
7660
  throw new Error('Individual SEG frames are out of plane with respect to the first SEG frame. ' + 'This is not yet supported. Aborting segmentation loading.');
7614
7661
  }
@@ -7634,7 +7681,7 @@ function labelmapImagesFromBuffer_insertPixelDataPlanar(_ref0) {
7634
7681
  labelmapImagesFromBuffer_cs3dLogger.warn("No instance metadata for referenced image at frame : ".concat(i, "."));
7635
7682
  continue;
7636
7683
  }
7637
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
7684
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
7638
7685
  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. ');
7639
7686
  }
7640
7687
  const imageIdIndex = imageIdMaps.indices[stackImageId];
@@ -7703,7 +7750,7 @@ function labelmapImagesFromBuffer_insertPixelDataPlanar(_ref0) {
7703
7750
  const ImageOrientationPatientI = sharedPlaneOrientation || (PerFrameFunctionalGroups === null || PerFrameFunctionalGroups === void 0 || (_PerFrameFunctionalGr2 = PerFrameFunctionalGroups.PlaneOrientationSequence) === null || _PerFrameFunctionalGr2 === void 0 ? void 0 : _PerFrameFunctionalGr2.ImageOrientationPatient) || validOrientations[0];
7704
7751
  const view = readFromUnpackedChunks(pixelDataChunks, i * sliceLength, sliceLength);
7705
7752
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
7706
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7753
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7707
7754
  if (!alignedPixelDataI) {
7708
7755
  throw new Error('Individual Labelmap SEG frames are out of plane with respect to the first SEG frame. ' + 'This is not yet supported. Aborting segmentation loading.');
7709
7756
  }
@@ -7728,7 +7775,7 @@ function labelmapImagesFromBuffer_insertPixelDataPlanar(_ref0) {
7728
7775
  labelmapImagesFromBuffer_cs3dLogger.warn("No instance metadata for referenced image at frame : ".concat(i, "."));
7729
7776
  continue;
7730
7777
  }
7731
- if (Rows !== sourceImageMetadata.Rows || Columns !== sourceImageMetadata.Columns) {
7778
+ if (alignedPixelDataI.shape[0] !== sourceImageMetadata.Rows || alignedPixelDataI.shape[1] !== sourceImageMetadata.Columns) {
7732
7779
  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. ');
7733
7780
  }
7734
7781
  const imageIdIndex = imageIdMaps.indices[stackImageId];
@@ -7797,7 +7844,7 @@ const getAlignedPixelData = _ref1 => {
7797
7844
  const ImageOrientationPatientI = sharedImageOrientationPatient || PerFrameFunctionalGroups.PlaneOrientationSequence.ImageOrientationPatient;
7798
7845
  const view = readFromUnpackedChunks(pixelDataChunks, sequenceIndex * sliceLength, sliceLength);
7799
7846
  const pixelDataI2D = ndarray(view, [Rows, Columns]);
7800
- const alignedPixelDataI = Segmentation_4X_alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7847
+ const alignedPixelDataI = alignPixelDataWithSourceData(pixelDataI2D, ImageOrientationPatientI, validOrientations, tolerance);
7801
7848
  if (!alignedPixelDataI) {
7802
7849
  throw new Error('Individual SEG frames are out of plane with respect to the first SEG frame. ' + 'This is not yet supported. Aborting segmentation loading.');
7803
7850
  }
@@ -7987,8 +8034,8 @@ const getSegmentData = _ref14 => {
7987
8034
  });
7988
8035
  checkImageDimensions({
7989
8036
  metadataProvider,
7990
- Rows,
7991
- Columns,
8037
+ Rows: alignedPixelDataI.shape[0],
8038
+ Columns: alignedPixelDataI.shape[1],
7992
8039
  imageId: referencedImageId
7993
8040
  });
7994
8041
  const indexCache = [];
@@ -8187,8 +8234,6 @@ function getStructureSetModule(contour, segment) {
8187
8234
 
8188
8235
 
8189
8236
 
8190
- // EXTERNAL MODULE: ../../node_modules/@cornerstonejs/metadata/dist/esm/index.js + 28 modules
8191
- var metadata_dist_esm = __webpack_require__(34047);
8192
8237
  ;// CONCATENATED MODULE: ../../node_modules/@cornerstonejs/adapters/dist/esm/utilities/referencedMetadataProvider.js
8193
8238
 
8194
8239
 
@@ -8200,7 +8245,7 @@ function referencedMetadataProvider_ownKeys(e, r) { var t = Object.keys(e); if (
8200
8245
  function referencedMetadataProvider_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? referencedMetadataProvider_ownKeys(Object(t), !0).forEach(function (r) { (0,defineProperty/* ["default"] */.A)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : referencedMetadataProvider_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8201
8246
  const referencedMetadataProvider_DicomMetaDictionary = dcmjs_es/* ["default"].data.DicomMetaDictionary */.Ay.data.DicomMetaDictionary;
8202
8247
  const referencedMetadataProvider_MetadataModules = esm.Enums.MetadataModules;
8203
- const definedAttributesOf = metadata_dist_esm/* .utilities.definedAttributesOf */.BF.Kx;
8248
+ const definedAttributesOf = dist_esm/* .utilities.definedAttributesOf */.BF.Kx;
8204
8249
  const referencedMetadataProvider_cs3dLogger = esm.utilities.logger.adaptersLog.getLogger('utilities.referencedMetadataProvider');
8205
8250
  const STUDY_MODULES = [referencedMetadataProvider_MetadataModules.GENERAL_STUDY, referencedMetadataProvider_MetadataModules.PATIENT_STUDY, referencedMetadataProvider_MetadataModules.PATIENT];
8206
8251
  const SERIES_MODULES = [referencedMetadataProvider_MetadataModules.GENERAL_SERIES];
@@ -8321,7 +8366,7 @@ esm.metaData.addProvider(referencedMetadataProvider_metadataProvider.get, 9023);
8321
8366
 
8322
8367
 
8323
8368
  const createInstance_MetadataModules = esm.Enums.MetadataModules;
8324
- const createInstance_definedAttributesOf = metadata_dist_esm/* .utilities.definedAttributesOf */.BF.Kx;
8369
+ const createInstance_definedAttributesOf = dist_esm/* .utilities.definedAttributesOf */.BF.Kx;
8325
8370
  function createInstance(instanceKey, studyExemplarImageId, base, options) {
8326
8371
  const _options$metadataProv = options.metadataProvider,
8327
8372
  metadataProvider = _options$metadataProv === void 0 ? esm.metaData : _options$metadataProv,
@@ -8361,7 +8406,7 @@ function createInstance(instanceKey, studyExemplarImageId, base, options) {
8361
8406
  function RTSS_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; }
8362
8407
  function RTSS_objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? RTSS_ownKeys(Object(t), !0).forEach(function (r) { (0,defineProperty/* ["default"] */.A)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : RTSS_ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8363
8408
  const RTSS_cs3dLogger = esm.utilities.logger.adaptersLog.getLogger('Cornerstone3D.RTStruct.RTSS');
8364
- const _utilities$contours = dist_esm.utilities.contours,
8409
+ const _utilities$contours = tools_dist_esm.utilities.contours,
8365
8410
  generateContourSetsFromLabelmap = _utilities$contours.generateContourSetsFromLabelmap,
8366
8411
  AnnotationToPointData = _utilities$contours.AnnotationToPointData;
8367
8412
  const RTSS_MetadataModules = esm.Enums.MetadataModules;
@@ -8488,7 +8533,7 @@ function generateRTSSFromContour(segmentations, options) {
8488
8533
  const annotations = [];
8489
8534
  for (const annotationSet of annotationUIDsMap.values()) {
8490
8535
  for (const annotationUID of annotationSet.values()) {
8491
- const annotation$1 = dist_esm.annotation.state.getAnnotation(annotationUID);
8536
+ const annotation$1 = tools_dist_esm.annotation.state.getAnnotation(annotationUID);
8492
8537
  if (!annotation$1) {
8493
8538
  RTSS_cs3dLogger.error('Unable to find an annotation for UID', annotationUID);
8494
8539
  continue;
@@ -8515,7 +8560,7 @@ function generateRTSSFromRepresentation(segmentations) {
8515
8560
 
8516
8561
 
8517
8562
 
8518
- const RTStruct_generateContourSetsFromLabelmap = dist_esm.utilities.contours.generateContourSetsFromLabelmap;
8563
+ const RTStruct_generateContourSetsFromLabelmap = tools_dist_esm.utilities.contours.generateContourSetsFromLabelmap;
8519
8564
 
8520
8565
 
8521
8566