All files / tools/src/utilities/segmentation createMergedLabelmapForIndex.ts

85% Statements 17/20
75% Branches 9/12
100% Functions 3/3
84.21% Lines 16/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71                                      8x 8x                   8x     8x   8x   8x 8x 8x 8x 13860864x 187226x         8x                 8x     8x       8x     8x        
import type { Types } from '@cornerstonejs/core';
import { volumeLoader, utilities as csUtils, cache } from '@cornerstonejs/core';
 
/**
 * Given a list of labelmaps (with the possibility of overlapping regions), and
 * a segmentIndex it creates a new labelmap with the same dimensions as the input labelmaps,
 * but merges them into a single labelmap for the segmentIndex. It wipes out
 * all other segment Indices. This is useful for calculating statistics regarding
 * a specific segment when there are overlapping regions between labelmap (e.g. TMTV)
 *
 * @param labelmaps - Array of labelmaps
 * @param segmentIndex - The segment index to merge
 * @returns Merged labelmap
 */
function createMergedLabelmapForIndex(
  labelmaps: Array<Types.IImageVolume>,
  segmentIndex = 1,
  volumeId = 'mergedLabelmap'
): Types.IImageVolume {
  labelmaps.forEach(({ direction, dimensions, origin, spacing }) => {
    Iif (
      !csUtils.isEqual(dimensions, labelmaps[0].dimensions) ||
      !csUtils.isEqual(direction, labelmaps[0].direction) ||
      !csUtils.isEqual(spacing, labelmaps[0].spacing) ||
      !csUtils.isEqual(origin, labelmaps[0].origin)
    ) {
      throw new Error('labelmaps must have the same size and shape');
    }
  });
 
  const labelmap = labelmaps[0];
 
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const arrayType = labelmap.voxelManager.getConstructor() as any;
 
  const outputData = new arrayType(labelmap.voxelManager.getScalarDataLength());
 
  labelmaps.forEach((labelmap) => {
    const voxelManager = labelmap.voxelManager;
    const scalarDataLength = voxelManager.getScalarDataLength();
    for (let i = 0; i < scalarDataLength; i++) {
      if (voxelManager.getAtIndex(i) === segmentIndex) {
        outputData[i] = segmentIndex;
      }
    }
  });
 
  const options = {
    scalarData: outputData,
    metadata: labelmap.metadata,
    spacing: labelmap.spacing,
    origin: labelmap.origin,
    direction: labelmap.direction,
    dimensions: labelmap.dimensions,
  };
 
  const cachedVolume = cache.getVolume(volumeId);
 
  let mergedVolume;
  Iif (cachedVolume) {
    mergedVolume = cachedVolume;
    mergedVolume.voxelManager.setCompleteScalarDataArray(outputData);
  } else {
    mergedVolume = volumeLoader.createLocalVolume(volumeId, options);
  }
 
  return mergedVolume;
}
 
export default createMergedLabelmapForIndex;