All files / packages/core/src/RenderingEngine/helpers setDefaultVolumeVOI.ts

3.03% Statements 2/66
0% Branches 0/46
0% Functions 0/6
3.03% Lines 2/66

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253                        1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
import {
  VolumeActor,
  IImageVolume,
  VOIRange,
  ScalingParameters,
} from '../../types';
import { loadAndCacheImage } from '../../loaders/imageLoader';
import * as metaData from '../../metaData';
import { getMinMax, windowLevel } from '../../utilities';
import { RequestType } from '../../enums';
import cache from '../../cache';
 
const PRIORITY = 0;
const REQUEST_TYPE = RequestType.Prefetch;
 
/**
 * It sets the default window level of an image volume based on the VOI.
 * It first look for the VOI in the metadata and if it is not found, it
 * loads the middle slice image (middle imageId) and based on its min
 * and max pixel values, it calculates the VOI.
 * Finally it sets the VOI on the volumeActor transferFunction
 * @param volumeActor - The volume actor
 * @param imageVolume - The image volume that we want to set the VOI for.
 */
async function setDefaultVolumeVOI(
  volumeActor: VolumeActor,
  imageVolume: IImageVolume,
  useNativeDataType: boolean
): Promise<void> {
  let voi = getVOIFromMetadata(imageVolume);
 
  if (!voi) {
    voi = await getVOIFromMinMax(imageVolume, useNativeDataType);
  }
 
  if (!voi || voi.lower === undefined || voi.upper === undefined) {
    throw new Error(
      'Could not get VOI from metadata, nor from the min max of the image middle slice'
    );
  }
 
  voi = handlePreScaledVolume(imageVolume, voi);
  const { lower, upper } = voi;
 
  if (lower === 0 && upper === 0) {
    return;
  }
 
  volumeActor
    .getProperty()
    .getRGBTransferFunction(0)
    .setMappingRange(lower, upper);
}
 
function handlePreScaledVolume(imageVolume: IImageVolume, voi: VOIRange) {
  const imageIds = imageVolume.imageIds;
  const imageIdIndex = Math.floor(imageIds.length / 2);
  const imageId = imageIds[imageIdIndex];
 
  const generalSeriesModule =
    metaData.get('generalSeriesModule', imageId) || {};
 
  /**
   * If the volume is prescaled and the modality is PT Sometimes you get super high
   * values at the peak and it skews the min/max so nothing useful is displayed
   * Therefore, we follow the majority of other viewers and we set the min/max
   * for the scaled PT to be 0, 5
   */
  if (_isCurrentImagePTPrescaled(generalSeriesModule.modality, imageVolume)) {
    return {
      lower: 0,
      upper: 5,
    };
  }
 
  return voi;
}
 
/**
 * Get the VOI from the metadata of the middle slice of the image volume. It checks
 * the metadata for the VOI and if it is not found, it returns null
 *
 * @param imageVolume - The image volume that we want to get the VOI from.
 * @returns VOIRange with lower and upper values
 */
function getVOIFromMetadata(imageVolume: IImageVolume): VOIRange {
  const { imageIds } = imageVolume;
 
  const imageIdIndex = Math.floor(imageIds.length / 2);
  const imageId = imageIds[imageIdIndex];
 
  const voiLutModule = metaData.get('voiLutModule', imageId);
 
  if (voiLutModule && voiLutModule.windowWidth && voiLutModule.windowCenter) {
    const { windowWidth, windowCenter } = voiLutModule;
 
    const voi = {
      windowWidth: Array.isArray(windowWidth) ? windowWidth[0] : windowWidth,
      windowCenter: Array.isArray(windowCenter)
        ? windowCenter[0]
        : windowCenter,
    };
 
    const { lower, upper } = windowLevel.toLowHighRange(
      Number(voi.windowWidth),
      Number(voi.windowCenter)
    );
 
    return {
      lower,
      upper,
    };
  }
}
 
/**
 * It loads the middle slice image (middle imageId) and based on its min
 * and max pixel values, it calculates the VOI.
 *
 * @param imageVolume - The image volume that we want to get the VOI from.
 * @returns The VOIRange with lower and upper values
 */
async function getVOIFromMinMax(
  imageVolume: IImageVolume,
  useNativeDataType: boolean
): Promise<VOIRange> {
  const { imageIds } = imageVolume;
  const scalarData = imageVolume.getScalarData();
 
  // Get the middle image from the list of imageIds
  const imageIdIndex = Math.floor(imageIds.length / 2);
  const imageId = imageVolume.imageIds[imageIdIndex];
  const generalSeriesModule =
    metaData.get('generalSeriesModule', imageId) || {};
  const { modality } = generalSeriesModule;
  const modalityLutModule = metaData.get('modalityLutModule', imageId) || {};
 
  const numImages = imageIds.length;
  const bytesPerImage = scalarData.byteLength / numImages;
  const voxelsPerImage = scalarData.length / numImages;
  const bytePerPixel = scalarData.BYTES_PER_ELEMENT;
 
  const scalingParameters: ScalingParameters = {
    rescaleSlope: modalityLutModule.rescaleSlope,
    rescaleIntercept: modalityLutModule.rescaleIntercept,
    modality,
  };
 
  let scalingParametersToUse;
  if (modality === 'PT') {
    const suvFactor = metaData.get('scalingModule', imageId);
 
    if (suvFactor) {
      scalingParametersToUse = {
        ...scalingParameters,
        suvbw: suvFactor.suvbw,
      };
    }
  }
 
  const byteOffset = imageIdIndex * bytesPerImage;
 
  const options = {
    targetBuffer: {
      type: useNativeDataType ? undefined : 'Float32Array',
    },
    priority: PRIORITY,
    requestType: REQUEST_TYPE,
    useNativeDataType,
    preScale: {
      enabled: true,
      scalingParameters: scalingParametersToUse,
    },
  };
 
  // Loading the middle slice image for a volume has two scenarios, the first one is that
  // uses the same volumeLoader which might not resolve to an image (since for performance
  // reasons volumes' pixelData is set via offset and length on the volume arrayBuffer
  // when each slice is loaded). The second scenario is that the image might not reach
  // to the volumeLoader, and an already cached image (with Image object) is used
  // instead. For the first scenario, we use the arrayBuffer of the volume to get the correct
  // slice for the imageScalarData, and for the second scenario we use the getPixelData
  // on the Cornerstone IImage object to get the pixel data.
  // Note: we don't want to use the derived or generated images for setting the
  // default VOI, because they are not the original. This is ugly but don't
  // know how to do it better.
  let image = cache.getImage(imageId);
 
  if (!imageVolume.referencedImageIds?.length) {
    // we should ignore the cache here,
    // since we want to load the image from with the most
    // recent prescale settings
    image = await loadAndCacheImage(imageId, { ...options, ignoreCache: true });
  }
 
  const imageScalarData = image
    ? image.getPixelData()
    : _getImageScalarDataFromImageVolume(
        imageVolume,
        byteOffset,
        bytePerPixel,
        voxelsPerImage
      );
 
  // Get the min and max pixel values of the middle slice
  const { min, max } = getMinMax(imageScalarData);
 
  return {
    lower: min,
    upper: max,
  };
}
 
function _getImageScalarDataFromImageVolume(
  imageVolume,
  byteOffset,
  bytePerPixel,
  voxelsPerImage
) {
  const { scalarData } = imageVolume;
  const { volumeBuffer } = scalarData;
  if (scalarData.BYTES_PER_ELEMENT !== bytePerPixel) {
    byteOffset *= scalarData.BYTES_PER_ELEMENT / bytePerPixel;
  }
 
  const TypedArray = scalarData.constructor;
  const imageScalarData = new TypedArray(voxelsPerImage);
 
  const volumeBufferView = new TypedArray(
    volumeBuffer,
    byteOffset,
    voxelsPerImage
  );
 
  imageScalarData.set(volumeBufferView);
 
  return imageScalarData;
}
 
function _isCurrentImagePTPrescaled(modality, imageVolume) {
  if (modality !== 'PT' || !imageVolume.isPreScaled) {
    return false;
  }
 
  if (!imageVolume.scaling?.PT.suvbw) {
    return false;
  }
 
  return true;
}
 
export default setDefaultVolumeVOI;