Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/components/VolumeRendering.vue
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,11 @@ export default defineComponent({
return [0, 1];
});

// The store refits a relative preset's opacity range once a streaming image loads.
const fullMappingRange = computed(
() =>
getColorFunctionRangeFromPreset(selectedPreset.value || '') ||
opacityFunction.value?.mappingRange ||
imageDataRange.value
);
const fullMappingRangeWidth = computed(() => {
Expand Down
28 changes: 10 additions & 18 deletions src/composables/useVolumeThumbnailing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ import { onBeforeUnmount, reactive, ref, watch } from 'vue';
import { Mode as LookupTableProxyMode } from '@kitware/vtk.js/Proxy/Core/LookupTableProxy';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import vtkPiecewiseFunctionProxy from '@kitware/vtk.js/Proxy/Core/PiecewiseFunctionProxy';
import { getPresetByName } from '@/src/types/color-map-preset';
import { createVolumeThumbnailer } from '../core/thumbnailers/volume-thumbnailer';
import { useCameraOrientation } from './useCameraOrientation';
import { useImageStore } from '../store/datasets-images';
import { useCurrentImage } from './useCurrentImage';
import {
getColorFunctionRangeFromPreset,
getOpacityRangeFromPreset,
getRelativePresetRange,
getShiftedOpacityFromPreset,
RELATIVE_PRESET_GAUSSIANS,
} from '../utils/vtk-helpers';
import { PresetNameList } from '../vtk/ColorMaps';
import { logError } from '../utils/loggers';
Expand All @@ -22,23 +24,13 @@ function resetOpacityFunction(
// reset pwf proxy range
pwfProxy.setDataRange(...dataRange);

const preset = getPresetByName(presetName);
if (preset?.OpacityPoints) {
const OpacityPoints = preset.OpacityPoints;
const points = [];
for (let i = 0; i < OpacityPoints.length; i += 2) {
points.push([OpacityPoints[i], OpacityPoints[i + 1]]);
}

const [xmin, xmax] = dataRange;
const width = xmax - xmin;
const pointsNormalized = points.map(([x, y]) => [(x - xmin) / width, y]);

const points = getShiftedOpacityFromPreset(presetName, dataRange, 0, 0);
if (points) {
pwfProxy.setMode(vtkPiecewiseFunctionProxy.Mode.Points);
pwfProxy.setPoints(pointsNormalized);
pwfProxy.setPoints(points);
} else {
pwfProxy.setMode(vtkPiecewiseFunctionProxy.Mode.Gaussians);
pwfProxy.setGaussians(vtkPiecewiseFunctionProxy.Defaults.Gaussians);
pwfProxy.setGaussians(RELATIVE_PRESET_GAUSSIANS);
}
}

Expand Down Expand Up @@ -75,7 +67,7 @@ export function useVolumeThumbnailing(
interruptSentinel = localSentinel;

thumbnailer.setInputImage(image);
const imageDataRange = image.getPointData().getScalars().getRange();
const relativeRange = getRelativePresetRange(image);

async function helper(presetName: string) {
// bail if a new thumbnail process has started
Expand All @@ -99,15 +91,15 @@ export function useVolumeThumbnailing(
const opRange = getOpacityRangeFromPreset(presetName);
resetOpacityFunction(
thumbnailer.opacityFuncProxy,
opRange || imageDataRange,
opRange || relativeRange,
presetName
);

thumbnailer.colorTransferFuncProxy.setMode(LookupTableProxyMode.Preset);
thumbnailer.colorTransferFuncProxy.setPresetName(presetName);
const ctRange = getColorFunctionRangeFromPreset(presetName);
thumbnailer.colorTransferFuncProxy.setDataRange(
...(ctRange || imageDataRange)
...(ctRange || relativeRange)
);

thumbnailer.resetCameraWithOrientation(
Expand Down
3 changes: 3 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ export const DEFAULT_PRESET_BY_MODALITY: Record<string, string> = {

export const DEFAULT_PRESET = 'CT-AAA';

// Maps onto each image's robust scalar range.
export const DEFAULT_GRAYSCALE_PRESET = 'Grayscale';

// Keyboard shortcuts/hotkeys. Can add modifiers: 'Shift+Ctrl+a'
export const ACTION_TO_KEY = {
windowLevel: 'l',
Expand Down
110 changes: 73 additions & 37 deletions src/store/view-configs/volume-coloring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import vtkPiecewiseFunctionProxy from '@kitware/vtk.js/Proxy/Core/PiecewiseFunct
import {
getColorFunctionRangeFromPreset,
getOpacityFunctionFromPreset,
getRelativePresetRange,
hasVisibleOpacity,
} from '@/src/utils/vtk-helpers';
import { DEFAULT_PRESET_BY_MODALITY, DEFAULT_PRESET } from '@/src/config';
import { ColorTransferFunction } from '@/src/types/views';
import {
DEFAULT_GRAYSCALE_PRESET,
DEFAULT_PRESET_BY_MODALITY,
DEFAULT_PRESET,
} from '@/src/config';
import { defineStore } from 'pinia';
import { reactive } from 'vue';
import { getCurrentScope, reactive, watch } from 'vue';
import {
DoubleKeyRecord,
deleteSecondKey,
Expand All @@ -17,6 +22,7 @@ import {
import { DeepPartial, Maybe } from '@/src/types';
import { identity } from '@/src/utils';
import { getDeclaredModality } from '@/src/utils/declaredModality';
import { looksLikeHounsfieldRange } from '@/src/utils/hounsfieldRange';
import { useImageCacheStore } from '@/src/store/image-cache';
import { createViewConfigSerializer } from './common';
import { ViewConfig } from '../../io/state-file/schema';
Expand All @@ -29,32 +35,31 @@ export const DEFAULT_SPECULAR = 0.3;
export const DEFAULT_EDGE_GRADIENT = 0.2;
export const DEFAULT_SAMPLING_DISTANCE = 0.2;

function getPresetFromImageModality(imageID: string) {
function getDeclaredPreset(imageID: string) {
const modality = getDeclaredModality(
useDICOMStore().volumeInfo[imageID]?.Modality,
useImageCacheStore().imageById[imageID]?.headerMetadata
);
return DEFAULT_PRESET_BY_MODALITY[modality] ?? DEFAULT_PRESET;
return DEFAULT_PRESET_BY_MODALITY[modality];
}

/**
* Gets partial color and opacity function configs from a preset.
* @param preset
* @returns
* Checks against the scalar range need every voxel, so a streaming image keeps
* its declared preset, or the CT guess, for good.
*/
function getColorAndOpacityFuncsFromPreset(preset: string) {
const ctFunc: Partial<ColorTransferFunction> = {
preset,
};

const ctRange = getColorFunctionRangeFromPreset(preset);
if (ctRange) {
ctFunc.mappingRange = ctRange;
}

const opFunc = getOpacityFunctionFromPreset(preset);

return { colorFunc: ctFunc, opacityFunc: opFunc };
function getDefaultPreset(imageID: string, image: vtkImageData) {
const declared = getDeclaredPreset(imageID);
const scalars = image.getPointData().getScalars();
if (
scalars.getNumberOfComponents() !== 1 ||
!useImageCacheStore().imageById[imageID]?.isLoaded()
)
return declared ?? DEFAULT_PRESET;
const range = scalars.getRange();
const fits = declared
? hasVisibleOpacity(declared, range)
: looksLikeHounsfieldRange(range);
return fits ? (declared ?? DEFAULT_PRESET) : DEFAULT_GRAYSCALE_PRESET;
}

export const defaultVolumeColorConfig = (): VolumeColorConfig => ({
Expand Down Expand Up @@ -134,42 +139,73 @@ export const useVolumeColoringStore = defineStore('volumeColoring', () => {
const updateOpacityFunction = createUpdateFunc('opacityFunction');
const updateCVRParameters = createUpdateFunc('cvr');

const storeScope = getCurrentScope();
const pendingRefits = new Map<string, () => void>();

// A range fitted to a streaming image's partial voxels is refit once it loads.
const refitWhenLoaded = (viewID: string, imageID: string, preset: string) => {
const key = JSON.stringify([viewID, imageID]);
pendingRefits.get(key)?.();
const imageCacheStore = useImageCacheStore();
const stop = storeScope!.run(() =>
watch(
() => imageCacheStore.imageById[imageID]?.isLoaded() ?? true,
(settled) => {
if (!settled) return;
stop?.();
pendingRefits.delete(key);
if (
imageCacheStore.getVtkImageData(imageID) &&
getConfig(viewID, imageID)?.transferFunction.preset === preset
)
setColorPreset(viewID, imageID, preset);
}
)
);
if (stop) pendingRefits.set(key, stop);
};

const setColorPreset = (viewID: string, imageID: string, preset: string) => {
const imageCacheStore = useImageCacheStore();
const image = imageCacheStore.getVtkImageData(imageID);
if (!image) throw new Error('Invalid imageID');

const imageDataRange = image.getPointData().getScalars().getRange();
const { colorFunc, opacityFunc } =
getColorAndOpacityFuncsFromPreset(preset);
colorFunc.mappingRange ||= imageDataRange;

const completeOpacityFunc = {
...opacityFunc,
mappingRange: imageDataRange,
};
const presetRange = getColorFunctionRangeFromPreset(preset);
// Absolute opacity points stay in scalar units, edited over the data range.
const opacityRange = presetRange
? image.getPointData().getScalars().getRange()
: getRelativePresetRange(image);

updateColorTransferFunction(viewID, imageID, colorFunc);
updateOpacityFunction(viewID, imageID, completeOpacityFunc);
updateColorTransferFunction(viewID, imageID, {
preset,
mappingRange: presetRange ?? opacityRange,
});
updateOpacityFunction(viewID, imageID, {
...getOpacityFunctionFromPreset(preset),
mappingRange: opacityRange,
});
if (!presetRange && !imageCacheStore.imageById[imageID]?.isLoaded())
refitWhenLoaded(viewID, imageID, preset);
};

const getInitialPreset = (dataID: string, image: vtkImageData) =>
defaultConfigs[dataID]?.transferFunction?.preset ??
getDefaultPreset(dataID, image);

const resetToDefaultColoring = (
viewID: string,
dataID: string,
image: vtkImageData
) => {
const defaults = defaultConfigs[dataID];
const preset = getInitialPreset(dataID, image);
const scalars = image.getPointData().getScalars();

updateColorBy(viewID, dataID, {
arrayName: defaults?.colorBy?.arrayName ?? scalars.getName(),
location: defaults?.colorBy?.location ?? 'pointData',
});
setColorPreset(
viewID,
dataID,
defaults?.transferFunction?.preset ?? getPresetFromImageModality(dataID)
);
setColorPreset(viewID, dataID, preset);
};

/**
Expand Down
16 changes: 16 additions & 0 deletions src/utils/__tests__/hounsfieldRange.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import '@/src/vtk/ColorMaps';
import { looksLikeHounsfieldRange } from '@/src/utils/hounsfieldRange';

describe('looksLikeHounsfieldRange', () => {
it.each([
['CT with air', [-1024, 3071], true],
['CT with scanner padding', [-3024, 1500], true],
['resampled CT', [-800, 1200], true],
['magnitude MR', [0, 4000], false],
['normalized intensities', [-3, 5], false],
['air without denser tissue', [-1000, 50], false],
] as const)('%s', (_, range, expected) => {
expect(looksLikeHounsfieldRange(range)).toBe(expected);
});
});
38 changes: 38 additions & 0 deletions src/utils/__tests__/robustScalarRange.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import { robustScalarRange } from '@/src/utils/robustScalarRange';

const range = (values: number[]) =>
robustScalarRange(values, [Math.min(...values), Math.max(...values)]);

describe('robustScalarRange', () => {
it('ignores a dominant background and clips outliers', () => {
const values = [
...new Array(9000).fill(0),
...Array.from({ length: 1000 }, (_, index) => 100 + (index % 100)),
1e6,
];
expect(range(values)).toEqual([101, 199]);
});

it('ramps a binary mask up from its background', () => {
expect(range([0, 0, 0, 1])).toEqual([0, 1]);
});

it('returns the full range of a constant image', () => {
expect(robustScalarRange(new Float32Array(8).fill(3), [3, 3])).toEqual([
3, 3,
]);
});

it('skips non-finite intensities', () => {
expect(
robustScalarRange([NaN, Infinity, 0, 0.25, 0.5, 0.75], [0, Infinity])
).toEqual([0.25, 0.75]);
});

it('falls back to the known range when sampling misses the foreground', () => {
const values = new Uint8Array(2 ** 20);
values[12345] = 200;
expect(robustScalarRange(values, [0, 200])).toEqual([0, 200]);
});
});
10 changes: 10 additions & 0 deletions src/utils/hounsfieldRange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { DEFAULT_PRESET } from '@/src/config';
import { hasVisibleOpacity } from '@/src/utils/vtk-helpers';

// Air is -1000 HU. Halfway to fat (-100) survives smoothing and resampling,
// while magnitude MR and normalized intensities stay above it.
const AIR_LEVEL = -500;

/** Whether an untagged scalar range reads as CT in Hounsfield units. */
export const looksLikeHounsfieldRange = (range: readonly [number, number]) =>
range[0] <= AIR_LEVEL && hasVisibleOpacity(DEFAULT_PRESET, range);
40 changes: 40 additions & 0 deletions src/utils/robustScalarRange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const SAMPLE_BUDGET = 2 ** 17;
const TAIL_PERCENT = 1;

function sampleValues(values: ArrayLike<number>) {
const count = Math.min(values.length, SAMPLE_BUDGET);
return Float64Array.from({ length: count }, (_, index) => {
// Jittered strata keep an integer stride from aliasing with the voxel grid.
let hash = Math.imul(index + 1, 0x9e3779b1);
hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b);
const offset = ((hash ^ (hash >>> 13)) >>> 0) / 0x100000000;
return values[Math.floor(((index + offset) * values.length) / count)];
});
}

/** The finite values of a deterministic sample, sorted ascending. */
export const sortedSample = (values: ArrayLike<number>) =>
sampleValues(values).filter(Number.isFinite).sort();

/**
* Percentile bounds of the sampled intensities above the minimum, which is
* treated as background. Falls back to `range` when no sample is above it.
*/
export function robustRangeOfSorted(
sorted: Float64Array,
range: readonly [number, number]
): [number, number] {
const start = sorted.findIndex((value) => value > sorted[0]);
if (start < 0) return [range[0], range[1]];
const foreground = sorted.subarray(start);
const tail = (TAIL_PERCENT / 100) * (foreground.length - 1);
const low = foreground[Math.floor(tail)];
const high = foreground[Math.ceil(foreground.length - 1 - tail)];
// A single foreground level, as in a binary mask, ramps up from background.
return low < high ? [low, high] : [sorted[0], high];
}

export const robustScalarRange = (
values: ArrayLike<number>,
range: readonly [number, number]
) => robustRangeOfSorted(sortedSample(values), range);
Loading
Loading