Skip to content

Commit 8b652d6

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. 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 8b652d6

11 files changed

Lines changed: 332 additions & 51 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: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { useCurrentImage } from './useCurrentImage';
1010
import {
1111
getColorFunctionRangeFromPreset,
1212
getOpacityRangeFromPreset,
13+
getRelativePresetRange,
14+
RELATIVE_PRESET_GAUSSIANS,
1315
} from '../utils/vtk-helpers';
1416
import { PresetNameList } from '../vtk/ColorMaps';
1517
import { logError } from '../utils/loggers';
@@ -38,7 +40,7 @@ function resetOpacityFunction(
3840
pwfProxy.setPoints(pointsNormalized);
3941
} else {
4042
pwfProxy.setMode(vtkPiecewiseFunctionProxy.Mode.Gaussians);
41-
pwfProxy.setGaussians(vtkPiecewiseFunctionProxy.Defaults.Gaussians);
43+
pwfProxy.setGaussians(RELATIVE_PRESET_GAUSSIANS);
4244
}
4345
}
4446

@@ -75,7 +77,7 @@ export function useVolumeThumbnailing(
7577
interruptSentinel = localSentinel;
7678

7779
thumbnailer.setInputImage(image);
78-
const imageDataRange = image.getPointData().getScalars().getRange();
80+
const relativeRange = getRelativePresetRange(image);
7981

8082
async function helper(presetName: string) {
8183
// bail if a new thumbnail process has started
@@ -99,15 +101,15 @@ export function useVolumeThumbnailing(
99101
const opRange = getOpacityRangeFromPreset(presetName);
100102
resetOpacityFunction(
101103
thumbnailer.opacityFuncProxy,
102-
opRange || imageDataRange,
104+
opRange || relativeRange,
103105
presetName
104106
);
105107

106108
thumbnailer.colorTransferFuncProxy.setMode(LookupTableProxyMode.Preset);
107109
thumbnailer.colorTransferFuncProxy.setPresetName(presetName);
108110
const ctRange = getColorFunctionRangeFromPreset(presetName);
109111
thumbnailer.colorTransferFuncProxy.setDataRange(
110-
...(ctRange || imageDataRange)
112+
...(ctRange || relativeRange)
111113
);
112114

113115
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: 44 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,14 @@ 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';
1015
import { reactive } from 'vue';
1116
import {
@@ -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 => ({
@@ -143,37 +148,40 @@ export const useVolumeColoringStore = defineStore('volumeColoring', () => {
143148
const image = imageCacheStore.getVtkImageData(imageID);
144149
if (!image) throw new Error('Invalid imageID');
145150

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

151-
const completeOpacityFunc = {
152-
...opacityFunc,
153-
mappingRange: imageDataRange,
154-
};
155-
156-
updateColorTransferFunction(viewID, imageID, colorFunc);
157-
updateOpacityFunction(viewID, imageID, completeOpacityFunc);
157+
updateColorTransferFunction(viewID, imageID, {
158+
preset,
159+
mappingRange: presetRange ?? opacityRange,
160+
});
161+
updateOpacityFunction(viewID, imageID, {
162+
...getOpacityFunctionFromPreset(preset),
163+
mappingRange: opacityRange,
164+
});
158165
};
159166

167+
const getInitialPreset = (dataID: string, image: vtkImageData) =>
168+
defaultConfigs[dataID]?.transferFunction?.preset ??
169+
getDefaultPreset(dataID, image);
170+
160171
const resetToDefaultColoring = (
161172
viewID: string,
162173
dataID: string,
163174
image: vtkImageData
164175
) => {
165176
const defaults = defaultConfigs[dataID];
177+
const preset = getInitialPreset(dataID, image);
166178
const scalars = image.getPointData().getScalars();
167179

168180
updateColorBy(viewID, dataID, {
169181
arrayName: defaults?.colorBy?.arrayName ?? scalars.getName(),
170182
location: defaults?.colorBy?.location ?? 'pointData',
171183
});
172-
setColorPreset(
173-
viewID,
174-
dataID,
175-
defaults?.transferFunction?.preset ?? getPresetFromImageModality(dataID)
176-
);
184+
setColorPreset(viewID, dataID, preset);
177185
};
178186

179187
/**
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: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
/**
16+
* Percentile bounds of the sampled intensities above the minimum, which is
17+
* treated as background. Falls back to `range` when no sample is above it.
18+
*/
19+
export function robustScalarRange(
20+
values: ArrayLike<number>,
21+
range: readonly [number, number]
22+
): [number, number] {
23+
const sorted = sampleValues(values).filter(Number.isFinite).sort();
24+
const start = sorted.findIndex((value) => value > sorted[0]);
25+
if (start < 0) return [range[0], range[1]];
26+
const foreground = sorted.subarray(start);
27+
const tail = (TAIL_PERCENT / 100) * (foreground.length - 1);
28+
const low = foreground[Math.floor(tail)];
29+
const high = foreground[Math.ceil(foreground.length - 1 - tail)];
30+
// A single foreground level, as in a binary mask, ramps up from background.
31+
return low < high ? [low, high] : [sorted[0], high];
32+
}

‎src/utils/vtk-helpers.ts‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import vtkFieldData from '@kitware/vtk.js/Common/DataModel/DataSetAttributes/FieldData';
1515
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
1616
import { Maybe } from '@/src/types';
17+
import { robustScalarRange } from '@/src/utils/robustScalarRange';
1718

1819
export function computeWorldToDisplay(
1920
xyz: Vector3,
@@ -153,6 +154,11 @@ export function getShiftedOpacityFromPreset(
153154
return null;
154155
}
155156

157+
// Zero at the bottom of the range, then fully opaque at and above the top.
158+
export const RELATIVE_PRESET_GAUSSIANS = [
159+
{ position: 1, height: 1, width: 1, xBias: 0, yBias: 1 },
160+
];
161+
156162
type OpacityFunctionWithoutRange =
157163
| Omit<OpacityGaussians, 'mappingRange'>
158164
| Omit<OpacityPoints, 'mappingRange'>
@@ -178,9 +184,7 @@ export function getOpacityFunctionFromPreset(
178184
return {
179185
mode: vtkPiecewiseFunctionProxy.Mode.Gaussians,
180186
// deep-copy necessary
181-
gaussians: JSON.parse(
182-
JSON.stringify(vtkPiecewiseFunctionProxy.Defaults.Gaussians)
183-
),
187+
gaussians: RELATIVE_PRESET_GAUSSIANS.map((gaussian) => ({ ...gaussian })),
184188
};
185189
}
186190

@@ -224,6 +228,41 @@ export function getColorFunctionRangeFromPreset(
224228
return null;
225229
}
226230

231+
/** The scalar range that a preset without an absolute range maps onto. */
232+
export function getRelativePresetRange(image: vtkImageData) {
233+
const scalars = image.getPointData().getScalars();
234+
const range = scalars.getRange();
235+
return scalars.getNumberOfComponents() === 1
236+
? robustScalarRange(scalars.getData(), range)
237+
: range;
238+
}
239+
240+
/** Whether a preset's opacity points are nonzero anywhere in a scalar range. */
241+
export function hasVisibleOpacity(
242+
presetName: string,
243+
[low, high]: readonly number[]
244+
) {
245+
const points = getPresetByName(presetName)?.OpacityPoints;
246+
if (!points) return true;
247+
const pairs = Array.from(
248+
{ length: points.length / 2 },
249+
(_, index) => [points[2 * index], points[2 * index + 1]] as const
250+
);
251+
// Piecewise linear and clamped, so the extremes lie at the ends or at points.
252+
const opacityAt = (value: number) => {
253+
const next = pairs.findIndex(([x]) => x >= value);
254+
if (next < 0) return pairs[pairs.length - 1][1];
255+
if (next === 0) return pairs[0][1];
256+
const [x0, y0] = pairs[next - 1];
257+
const [x1, y1] = pairs[next];
258+
return y0 + ((y1 - y0) * (value - x0)) / (x1 - x0);
259+
};
260+
return (
261+
[low, high].some((value) => opacityAt(value) > 0) ||
262+
pairs.some(([x, y]) => x >= low && x <= high && y > 0)
263+
);
264+
}
265+
227266
/**
228267
* Retrieves the effective opacity mapping range, if any.
229268
*

0 commit comments

Comments
 (0)