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

39.13% Statements 9/23
21.42% Branches 3/14
33.33% Functions 1/3
39.13% Lines 9/23

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                                        8x 8x         8x     8x 8x   8x 8x     8x 8x                                                              
import { cache } from '@cornerstonejs/core';
import { getSegmentation } from '../../stateManagement/segmentation/getSegmentation';
import type {
  LabelmapSegmentationDataStack,
  LabelmapSegmentationDataVolume,
} from '../../types';
import getOrCreateImageVolume from './getOrCreateImageVolume';
 
/**
 * Retrieves the reference volume associated with a segmentation volume.
 * This function first checks if the segmentation volume has a direct reference
 * to a volume via referencedVolumeId. If not, it attempts to find the reference
 * volume by looking up the first image in the segmentation's imageIds array,
 * then finding its referenced image and the volume containing that image.
 *
 * @param segmentationId - The ID of the segmentation
 * @returns The reference volume if found, or null if the segmentation volume
 * doesn't exist or no reference volume could be determined
 */
export function getReferenceVolumeForSegmentation(segmentationId: string) {
  const segmentation = getSegmentation(segmentationId);
  Iif (!segmentation) {
    return null;
  }
 
  let referenceImageIds: string[];
  const labelmap = segmentation.representationData.Labelmap;
 
  // Case 1: Labelmap with imageIds (stack-based)
  if ('imageIds' in labelmap) {
    const { imageIds } = labelmap;
 
    const firstImage = cache.getImage(imageIds[0]);
    const volumeInfo = cache.getVolumeContainingImageId(
      firstImage.referencedImageId
    );
    Eif (volumeInfo?.volume) {
      return volumeInfo.volume;
    }
 
    // Map image IDs to their referenced IDs
    referenceImageIds = imageIds.map(
      (imageId) => cache.getImage(imageId).referencedImageId
    );
  }
  // Case 2: Labelmap with volumeId (volume-based)
  else Eif ('volumeId' in labelmap) {
    const { volumeId, referencedVolumeId } = labelmap;
 
    // Try to get directly referenced volume
    if (referencedVolumeId) {
      const refVolume = cache.getVolume(referencedVolumeId);
      if (refVolume) {
        return refVolume;
      }
    }
 
    const segVolume = cache.getVolume(volumeId);
    if (segVolume) {
      referenceImageIds = segVolume.imageIds.map(
        (imageId) => cache.getImage(imageId).referencedImageId
      );
    }
  }
 
  // Create and return image volume from reference image IDs
  return getOrCreateImageVolume(referenceImageIds);
}