Skip to content

Commit 7478e9f

Browse files
committed
feat(volume-rendering): fit a grayscale default to untagged volumes
Single-component volumes without a declared modality now default to CT-AAA when their loaded scalar range reads as Hounsfield units (minimum at or below -500, with CT-AAA visible over it), and to the Grayscale preset otherwise. Presets without an absolute range map color and opacity onto a robust intensity range: percentile bounds of sampled voxels above the image minimum, so background and outliers do not compress the visible signal. The preset thumbnails and the 3D mapping range sliders use the same range. MR intensities have no standard scale, so the MR presets are fitted the same way instead of using fixed scalar values. A range fitted while an image is still streaming is refit once it finishes loading. The voxel sample behind the fitted range is cached until the scalars change. A declared modality whose preset is fully transparent over the data range, such as normalized intensities tagged CT, also falls back to Grayscale. Streaming images keep their declared preset, or CT-AAA, so the 3D view renders progressively.
1 parent 6e43e83 commit 7478e9f

11 files changed

Lines changed: 512 additions & 71 deletions

File tree

‎src/components/VolumeRendering.vue‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { useCurrentImage } from '@/src/composables/useCurrentImage';
2222
import useVolumeColoringStore from '@/src/store/view-configs/volume-coloring';
2323
import {
2424
getColorFunctionRangeFromPreset,
25+
getRelativePresetRange,
2526
getShiftedOpacityFromPreset,
2627
} from '@/src/utils/vtk-helpers';
2728
@@ -254,11 +255,13 @@ export default defineComponent({
254255
return [0, 1];
255256
});
256257
257-
const fullMappingRange = computed(
258-
() =>
258+
const fullMappingRange = computed(() => {
259+
const image = currentImageData.value;
260+
return (
259261
getColorFunctionRangeFromPreset(selectedPreset.value || '') ||
260-
imageDataRange.value
261-
);
262+
(image ? getRelativePresetRange(image) : imageDataRange.value)
263+
);
264+
});
262265
const fullMappingRangeWidth = computed(() => {
263266
const range = fullMappingRange.value;
264267
return range[1] - range[0];

‎src/composables/useVolumeThumbnailing.ts‎

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@ import { onBeforeUnmount, reactive, ref, watch } from 'vue';
22
import { Mode as LookupTableProxyMode } from '@kitware/vtk.js/Proxy/Core/LookupTableProxy';
33
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
44
import vtkPiecewiseFunctionProxy from '@kitware/vtk.js/Proxy/Core/PiecewiseFunctionProxy';
5-
import { getPresetByName } from '@/src/types/color-map-preset';
65
import { createVolumeThumbnailer } from '../core/thumbnailers/volume-thumbnailer';
76
import { useCameraOrientation } from './useCameraOrientation';
87
import { useImageStore } from '../store/datasets-images';
98
import { useCurrentImage } from './useCurrentImage';
109
import {
1110
getColorFunctionRangeFromPreset,
1211
getOpacityRangeFromPreset,
12+
getRelativePresetRange,
13+
getShiftedOpacityFromPreset,
14+
RELATIVE_PRESET_GAUSSIANS,
1315
} from '../utils/vtk-helpers';
1416
import { PresetNameList } from '../vtk/ColorMaps';
1517
import { logError } from '../utils/loggers';
@@ -22,23 +24,13 @@ function resetOpacityFunction(
2224
// reset pwf proxy range
2325
pwfProxy.setDataRange(...dataRange);
2426

25-
const preset = getPresetByName(presetName);
26-
if (preset?.OpacityPoints) {
27-
const OpacityPoints = preset.OpacityPoints;
28-
const points = [];
29-
for (let i = 0; i < OpacityPoints.length; i += 2) {
30-
points.push([OpacityPoints[i], OpacityPoints[i + 1]]);
31-
}
32-
33-
const [xmin, xmax] = dataRange;
34-
const width = xmax - xmin;
35-
const pointsNormalized = points.map(([x, y]) => [(x - xmin) / width, y]);
36-
27+
const points = getShiftedOpacityFromPreset(presetName, dataRange, 0, 0);
28+
if (points) {
3729
pwfProxy.setMode(vtkPiecewiseFunctionProxy.Mode.Points);
38-
pwfProxy.setPoints(pointsNormalized);
30+
pwfProxy.setPoints(points);
3931
} else {
4032
pwfProxy.setMode(vtkPiecewiseFunctionProxy.Mode.Gaussians);
41-
pwfProxy.setGaussians(vtkPiecewiseFunctionProxy.Defaults.Gaussians);
33+
pwfProxy.setGaussians(RELATIVE_PRESET_GAUSSIANS);
4234
}
4335
}
4436

@@ -75,7 +67,7 @@ export function useVolumeThumbnailing(
7567
interruptSentinel = localSentinel;
7668

7769
thumbnailer.setInputImage(image);
78-
const imageDataRange = image.getPointData().getScalars().getRange();
70+
const relativeRange = getRelativePresetRange(image);
7971

8072
async function helper(presetName: string) {
8173
// bail if a new thumbnail process has started
@@ -99,15 +91,15 @@ export function useVolumeThumbnailing(
9991
const opRange = getOpacityRangeFromPreset(presetName);
10092
resetOpacityFunction(
10193
thumbnailer.opacityFuncProxy,
102-
opRange || imageDataRange,
94+
opRange || relativeRange,
10395
presetName
10496
);
10597

10698
thumbnailer.colorTransferFuncProxy.setMode(LookupTableProxyMode.Preset);
10799
thumbnailer.colorTransferFuncProxy.setPresetName(presetName);
108100
const ctRange = getColorFunctionRangeFromPreset(presetName);
109101
thumbnailer.colorTransferFuncProxy.setDataRange(
110-
...(ctRange || imageDataRange)
102+
...(ctRange || relativeRange)
111103
);
112104

113105
thumbnailer.resetCameraWithOrientation(

‎src/config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,9 @@ export const DEFAULT_PRESET_BY_MODALITY: Record<string, string> = {
196196

197197
export const DEFAULT_PRESET = 'CT-AAA';
198198

199+
// Maps onto each image's robust scalar range.
200+
export const DEFAULT_GRAYSCALE_PRESET = 'Grayscale';
201+
199202
// Keyboard shortcuts/hotkeys. Can add modifiers: 'Shift+Ctrl+a'
200203
export const ACTION_TO_KEY = {
201204
windowLevel: 'l',

‎src/store/view-configs/volume-coloring.ts‎

Lines changed: 73 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,16 @@ import vtkPiecewiseFunctionProxy from '@kitware/vtk.js/Proxy/Core/PiecewiseFunct
33
import {
44
getColorFunctionRangeFromPreset,
55
getOpacityFunctionFromPreset,
6+
getRelativePresetRange,
7+
hasVisibleOpacity,
68
} from '@/src/utils/vtk-helpers';
7-
import { DEFAULT_PRESET_BY_MODALITY, DEFAULT_PRESET } from '@/src/config';
8-
import { ColorTransferFunction } from '@/src/types/views';
9+
import {
10+
DEFAULT_GRAYSCALE_PRESET,
11+
DEFAULT_PRESET_BY_MODALITY,
12+
DEFAULT_PRESET,
13+
} from '@/src/config';
914
import { defineStore } from 'pinia';
10-
import { reactive } from 'vue';
15+
import { getCurrentScope, reactive, watch } from 'vue';
1116
import {
1217
DoubleKeyRecord,
1318
deleteSecondKey,
@@ -18,6 +23,7 @@ import { DeepPartial, Maybe } from '@/src/types';
1823
import { identity } from '@/src/utils';
1924
import { isDicomImage } from '@/src/utils/dataSelection';
2025
import { getDeclaredModality } from '@/src/utils/declaredModality';
26+
import { looksLikeHounsfieldRange } from '@/src/utils/hounsfieldRange';
2127
import { useImageCacheStore } from '@/src/store/image-cache';
2228
import { createViewConfigSerializer } from './common';
2329
import { ViewConfig } from '../../io/state-file/schema';
@@ -30,35 +36,34 @@ export const DEFAULT_SPECULAR = 0.3;
3036
export const DEFAULT_EDGE_GRADIENT = 0.2;
3137
export const DEFAULT_SAMPLING_DISTANCE = 0.2;
3238

33-
function getPresetFromImageModality(imageID: string) {
39+
function getDeclaredPreset(imageID: string) {
3440
const dicomModality = isDicomImage(imageID)
3541
? useDICOMStore().volumeInfo[imageID]?.Modality
3642
: undefined;
3743
const modality = getDeclaredModality(
3844
dicomModality,
3945
useImageCacheStore().imageById[imageID]?.headerMetadata
4046
);
41-
return DEFAULT_PRESET_BY_MODALITY[modality] ?? DEFAULT_PRESET;
47+
return DEFAULT_PRESET_BY_MODALITY[modality];
4248
}
4349

4450
/**
45-
* Gets partial color and opacity function configs from a preset.
46-
* @param preset
47-
* @returns
51+
* Checks against the scalar range need every voxel, so a streaming image keeps
52+
* its declared preset, or the CT guess, for good.
4853
*/
49-
function getColorAndOpacityFuncsFromPreset(preset: string) {
50-
const ctFunc: Partial<ColorTransferFunction> = {
51-
preset,
52-
};
53-
54-
const ctRange = getColorFunctionRangeFromPreset(preset);
55-
if (ctRange) {
56-
ctFunc.mappingRange = ctRange;
57-
}
58-
59-
const opFunc = getOpacityFunctionFromPreset(preset);
60-
61-
return { colorFunc: ctFunc, opacityFunc: opFunc };
54+
function getDefaultPreset(imageID: string, image: vtkImageData) {
55+
const declared = getDeclaredPreset(imageID);
56+
const scalars = image.getPointData().getScalars();
57+
if (
58+
scalars.getNumberOfComponents() !== 1 ||
59+
!useImageCacheStore().imageById[imageID]?.isLoaded()
60+
)
61+
return declared ?? DEFAULT_PRESET;
62+
const range = scalars.getRange();
63+
const fits = declared
64+
? hasVisibleOpacity(declared, range)
65+
: looksLikeHounsfieldRange(range);
66+
return fits ? (declared ?? DEFAULT_PRESET) : DEFAULT_GRAYSCALE_PRESET;
6267
}
6368

6469
export const defaultVolumeColorConfig = (): VolumeColorConfig => ({
@@ -138,42 +143,73 @@ export const useVolumeColoringStore = defineStore('volumeColoring', () => {
138143
const updateOpacityFunction = createUpdateFunc('opacityFunction');
139144
const updateCVRParameters = createUpdateFunc('cvr');
140145

146+
const storeScope = getCurrentScope();
147+
const pendingRefits = new Map<string, () => void>();
148+
149+
// A range fitted to a streaming image's partial voxels is refit once it loads.
150+
const refitWhenLoaded = (viewID: string, imageID: string, preset: string) => {
151+
const key = JSON.stringify([viewID, imageID]);
152+
pendingRefits.get(key)?.();
153+
const imageCacheStore = useImageCacheStore();
154+
const stop = storeScope!.run(() =>
155+
watch(
156+
() => imageCacheStore.imageById[imageID]?.isLoaded() ?? true,
157+
(settled) => {
158+
if (!settled) return;
159+
stop?.();
160+
pendingRefits.delete(key);
161+
if (
162+
imageCacheStore.getVtkImageData(imageID) &&
163+
getConfig(viewID, imageID)?.transferFunction.preset === preset
164+
)
165+
setColorPreset(viewID, imageID, preset);
166+
}
167+
)
168+
);
169+
if (stop) pendingRefits.set(key, stop);
170+
};
171+
141172
const setColorPreset = (viewID: string, imageID: string, preset: string) => {
142173
const imageCacheStore = useImageCacheStore();
143174
const image = imageCacheStore.getVtkImageData(imageID);
144175
if (!image) throw new Error('Invalid imageID');
145176

146-
const imageDataRange = image.getPointData().getScalars().getRange();
147-
const { colorFunc, opacityFunc } =
148-
getColorAndOpacityFuncsFromPreset(preset);
149-
colorFunc.mappingRange ||= imageDataRange;
150-
151-
const completeOpacityFunc = {
152-
...opacityFunc,
153-
mappingRange: imageDataRange,
154-
};
177+
const presetRange = getColorFunctionRangeFromPreset(preset);
178+
// Absolute opacity points stay in scalar units, edited over the data range.
179+
const opacityRange = presetRange
180+
? image.getPointData().getScalars().getRange()
181+
: getRelativePresetRange(image);
155182

156-
updateColorTransferFunction(viewID, imageID, colorFunc);
157-
updateOpacityFunction(viewID, imageID, completeOpacityFunc);
183+
updateColorTransferFunction(viewID, imageID, {
184+
preset,
185+
mappingRange: presetRange ?? opacityRange,
186+
});
187+
updateOpacityFunction(viewID, imageID, {
188+
...getOpacityFunctionFromPreset(preset),
189+
mappingRange: opacityRange,
190+
});
191+
if (!presetRange && !imageCacheStore.imageById[imageID]?.isLoaded())
192+
refitWhenLoaded(viewID, imageID, preset);
158193
};
159194

195+
const getInitialPreset = (dataID: string, image: vtkImageData) =>
196+
defaultConfigs[dataID]?.transferFunction?.preset ??
197+
getDefaultPreset(dataID, image);
198+
160199
const resetToDefaultColoring = (
161200
viewID: string,
162201
dataID: string,
163202
image: vtkImageData
164203
) => {
165204
const defaults = defaultConfigs[dataID];
205+
const preset = getInitialPreset(dataID, image);
166206
const scalars = image.getPointData().getScalars();
167207

168208
updateColorBy(viewID, dataID, {
169209
arrayName: defaults?.colorBy?.arrayName ?? scalars.getName(),
170210
location: defaults?.colorBy?.location ?? 'pointData',
171211
});
172-
setColorPreset(
173-
viewID,
174-
dataID,
175-
defaults?.transferFunction?.preset ?? getPresetFromImageModality(dataID)
176-
);
212+
setColorPreset(viewID, dataID, preset);
177213
};
178214

179215
/**
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { describe, expect, it } from 'vitest';
2+
import '@/src/vtk/ColorMaps';
3+
import { looksLikeHounsfieldRange } from '@/src/utils/hounsfieldRange';
4+
5+
describe('looksLikeHounsfieldRange', () => {
6+
it.each([
7+
['CT with air', [-1024, 3071], true],
8+
['CT with scanner padding', [-3024, 1500], true],
9+
['resampled CT', [-800, 1200], true],
10+
['magnitude MR', [0, 4000], false],
11+
['normalized intensities', [-3, 5], false],
12+
['air without denser tissue', [-1000, 50], false],
13+
] as const)('%s', (_, range, expected) => {
14+
expect(looksLikeHounsfieldRange(range)).toBe(expected);
15+
});
16+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { robustScalarRange } from '@/src/utils/robustScalarRange';
3+
4+
const range = (values: number[]) =>
5+
robustScalarRange(values, [Math.min(...values), Math.max(...values)]);
6+
7+
describe('robustScalarRange', () => {
8+
it('ignores a dominant background and clips outliers', () => {
9+
const values = [
10+
...new Array(9000).fill(0),
11+
...Array.from({ length: 1000 }, (_, index) => 100 + (index % 100)),
12+
1e6,
13+
];
14+
expect(range(values)).toEqual([101, 199]);
15+
});
16+
17+
it('ramps a binary mask up from its background', () => {
18+
expect(range([0, 0, 0, 1])).toEqual([0, 1]);
19+
});
20+
21+
it('returns the full range of a constant image', () => {
22+
expect(robustScalarRange(new Float32Array(8).fill(3), [3, 3])).toEqual([
23+
3, 3,
24+
]);
25+
});
26+
27+
it('skips non-finite intensities', () => {
28+
expect(
29+
robustScalarRange([NaN, Infinity, 0, 0.25, 0.5, 0.75], [0, Infinity])
30+
).toEqual([0.25, 0.75]);
31+
});
32+
33+
it('falls back to the known range when sampling misses the foreground', () => {
34+
const values = new Uint8Array(2 ** 20);
35+
values[12345] = 200;
36+
expect(robustScalarRange(values, [0, 200])).toEqual([0, 200]);
37+
});
38+
});

‎src/utils/hounsfieldRange.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { DEFAULT_PRESET } from '@/src/config';
2+
import { hasVisibleOpacity } from '@/src/utils/vtk-helpers';
3+
4+
// Air is -1000 HU. Halfway to fat (-100) survives smoothing and resampling,
5+
// while magnitude MR and normalized intensities stay above it.
6+
const AIR_LEVEL = -500;
7+
8+
/** Whether an untagged scalar range reads as CT in Hounsfield units. */
9+
export const looksLikeHounsfieldRange = (range: readonly [number, number]) =>
10+
range[0] <= AIR_LEVEL && hasVisibleOpacity(DEFAULT_PRESET, range);

‎src/utils/robustScalarRange.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const SAMPLE_BUDGET = 2 ** 17;
2+
const TAIL_PERCENT = 1;
3+
4+
function sampleValues(values: ArrayLike<number>) {
5+
const count = Math.min(values.length, SAMPLE_BUDGET);
6+
return Float64Array.from({ length: count }, (_, index) => {
7+
// Jittered strata keep an integer stride from aliasing with the voxel grid.
8+
let hash = Math.imul(index + 1, 0x9e3779b1);
9+
hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b);
10+
const offset = ((hash ^ (hash >>> 13)) >>> 0) / 0x100000000;
11+
return values[Math.floor(((index + offset) * values.length) / count)];
12+
});
13+
}
14+
15+
/** The finite values of a deterministic sample, sorted ascending. */
16+
export const sortedSample = (values: ArrayLike<number>) =>
17+
sampleValues(values).filter(Number.isFinite).sort();
18+
19+
/**
20+
* Percentile bounds of the sampled intensities above the minimum, which is
21+
* treated as background. Falls back to `range` when no sample is above it.
22+
*/
23+
export function robustRangeOfSorted(
24+
sorted: Float64Array,
25+
range: readonly [number, number]
26+
): [number, number] {
27+
const start = sorted.findIndex((value) => value > sorted[0]);
28+
if (start < 0) return [range[0], range[1]];
29+
const foreground = sorted.subarray(start);
30+
const tail = (TAIL_PERCENT / 100) * (foreground.length - 1);
31+
const low = foreground[Math.floor(tail)];
32+
const high = foreground[Math.ceil(foreground.length - 1 - tail)];
33+
// A single foreground level, as in a binary mask, ramps up from background.
34+
return low < high ? [low, high] : [sorted[0], high];
35+
}
36+
37+
export const robustScalarRange = (
38+
values: ArrayLike<number>,
39+
range: readonly [number, number]
40+
) => robustRangeOfSorted(sortedSample(values), range);

0 commit comments

Comments
 (0)