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
31 changes: 20 additions & 11 deletions src/components/VolumeRendering.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import { useVolumeColoringInitializer } from '@/src/composables/useVolumeColorin
import { useResizeObserver } from '@/src/composables/useResizeObserver';
import { useCurrentImage } from '@/src/composables/useCurrentImage';
import useVolumeColoringStore from '@/src/store/view-configs/volume-coloring';
import { piecewiseHistogram } from '@/src/utils/histogram';
import {
getColorFunctionRangeFromPreset,
getScalarSample,
getShiftedOpacityFromPreset,
} from '@/src/utils/vtk-helpers';

Expand Down Expand Up @@ -183,19 +185,26 @@ export default defineComponent({
colorTransferFunc.delete();
});

watch(
currentImageData,
(image) => {
if (image) {
const scalars = image.getPointData().getScalars();
// TODO(fli): setDataArray() re-computes the data range unnecessarily
pwfWidget.setDataArray(scalars.getData());
pwfWidget.render();
}
},
{ immediate: true }
const opacityMappingRange = computed(
() => opacityFunction.value?.mappingRange
);

watchEffect(() => {
const image = currentImageData.value;
const range = opacityMappingRange.value;
if (!image || !range) return;
pwfWidget.setHistogram(
piecewiseHistogram(
getScalarSample(image),
range,
pwfWidget.getNumberOfBins(),
!image.getPointData().getScalars().getDataType().includes('Float')
),
range
);
pwfWidget.render();
});

// update pwf widget when lut changes
watch(
colorTransferFunctionRef,
Expand Down
36 changes: 35 additions & 1 deletion src/utils/__tests__/histogram.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
import { histogram, histogramWindowRanges } from '@/src/utils/histogram';
import {
histogram,
histogramWindowRanges,
piecewiseHistogram,
} from '@/src/utils/histogram';

describe('scalar image histograms', () => {
it('keeps inclusive integer source bins', () => {
Expand Down Expand Up @@ -40,3 +44,33 @@ describe('scalar image histograms', () => {
expect(() => histogram([1, -Infinity], [0, 1], 512)).toThrow(/finite/);
});
});

describe('piecewiseHistogram', () => {
it('uses one bin per level for integers narrower than the bin count', () => {
const levels = Array.from({ length: 161 }, (_, index) => 20 + index);
const counts = piecewiseHistogram(levels, [20, 180], 256, true);
expect(counts).toHaveLength(161);
expect(counts.every((count) => count > 0)).toBe(true);
expect(piecewiseHistogram(levels, [20, 180], 256)).toHaveLength(256);
});

it('draws the two levels of a binary mask as separate peaks', () => {
const mask = [...Array(9).fill(0), 1];
expect(Array.from(piecewiseHistogram(mask, [0, 1], 256, true))).toEqual([
9, 0, 1,
]);
});

it('bins only the given range and scales by the second-largest bin', () => {
const values = [-5, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 1e6, NaN];
expect(Array.from(piecewiseHistogram(values, [0, 4], 5))).toEqual([
2, 1, 0.5, 1, 0.5,
]);
});

it('is empty for a zero-width range', () => {
expect(Array.from(piecewiseHistogram([3, 3], [3, 3], 4))).toEqual([
0, 0, 0, 0,
]);
});
});
22 changes: 22 additions & 0 deletions src/utils/histogram.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,25 @@ export function histogramWindowRanges(
HighContrast: percentileRange(WLAutoRanges.HighContrast),
};
}

/** Bins and scaling as vtkPiecewiseGaussianWidget draws them: bin i at min + i * span / (bins - 1). */
export function piecewiseHistogram(
values: ArrayLike<number>,
[min, max]: readonly number[],
maxBins: number,
integer = false
) {
const span = max - min;
// One bin per integer level, as extra bins leave gaps; three at least so two levels draw as two peaks.
const numberOfBins = integer
? Math.max(3, Math.min(maxBins, Math.floor(span) + 1))
: maxBins;
const counts = new Float32Array(numberOfBins);
if (!(span > 0)) return counts;
for (let index = 0; index < values.length; index += 1) {
const bin = Math.floor(((numberOfBins - 1) * (values[index] - min)) / span);
if (bin >= 0 && bin < numberOfBins) counts[bin] += 1;
}
const scale = counts.slice().sort()[numberOfBins - 2] || 1;
return counts.map((count) => count / scale);
}
8 changes: 8 additions & 0 deletions src/vtk/PiecewiseWidget/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ function vtkPiecewiseWidget(publicAPI, model) {
model.opacityPointShift = 0;
model.opacityValueShift = 0;

publicAPI.setHistogram = (histogram, dataRange) => {
model.histogram = histogram;
model.dataRange = [...dataRange];
// The color bar is cached per transfer function mtime, not per range.
model.colorCanvasMTime = 0;
publicAPI.modified();
};

publicAPI.setGaussiansMode = () => {
model.pwMode = Mode.Gaussians;
};
Expand Down
10 changes: 2 additions & 8 deletions tests/specs/volume-coloring-reset.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
nrrd,
showColorPresets,
openWith3DLayout,
radialRamp,
selectedPreset,
writeNrrd,
} from './volumeTestUtils';
Expand Down Expand Up @@ -77,14 +78,7 @@ async function dragOpacityCurve(steps: number) {
describe('3D rendering color and opacity reset', () => {
it('restores Shift, Width, and the opacity curve while keeping lighting', async () => {
const name = 'volume-coloring-reset';
const voxels = floatVoxels(SIZE, (index) => {
const offsets = [
index % SIZE,
Math.floor(index / SIZE) % SIZE,
Math.floor(index / SIZE ** 2),
].map((c) => c - SIZE / 2);
return Math.max(0, 1000 * (1 - Math.hypot(...offsets) / (SIZE / 2)));
});
const voxels = floatVoxels(SIZE, radialRamp(SIZE));
await openWith3DLayout(
writeNrrd(name, nrrd(['modality:=MR'], 'float', SIZE), voxels),
name
Expand Down
62 changes: 62 additions & 0 deletions tests/specs/volume-opacity-histogram.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { volViewPage } from '../pageobjects/volview.page';
import { captureViewPixels, waitForModuleTransitions } from './utils';
import {
differingFraction,
floatVoxels,
nrrd,
openWith3DLayout,
radialRamp,
writeNrrd,
} from './volumeTestUtils';

const SIZE = 16;
const EDITOR = '[data-testid="volume-opacity-editor"]';

const ramp = radialRamp(SIZE);
const voxels = (corner: number) =>
floatVoxels(SIZE, (index) => (index === 0 ? corner : ramp(index)));

async function capture() {
const [{ data }] = await captureViewPixels(
EDITOR,
0,
'volume-opacity-histogram.png'
);
return data;
}

async function stableEditorPixels(name: string, data: Buffer) {
await openWith3DLayout(writeNrrd(name, nrrd([], 'float', SIZE), data), name);
await volViewPage.renderingModuleTab.waitForClickable();
await volViewPage.renderingModuleTab.click();
await waitForModuleTransitions();
await $(EDITOR).scrollIntoView({ block: 'center', behavior: 'instant' });
let previous = await capture();
await browser.waitUntil(async () => {
const next = await capture();
const same = next.equals(previous);
previous = next;
return same;
});
return previous;
}

describe('3D rendering opacity editor histogram', () => {
it('spans the fitted opacity range rather than a far outlier', async () => {
const plain = await stableEditorPixels(
'opacity-histogram-plain',
voxels(0)
);
const outlier = await stableEditorPixels(
'opacity-histogram-outlier',
voxels(1e6)
);
expect(differingFraction(plain, outlier)).toBeLessThan(0.01);
// A relative preset draws the same curve and color bar over any range, so only the histogram differs.
const squared = await stableEditorPixels(
'opacity-histogram-squared',
floatVoxels(SIZE, (index) => ramp(index) ** 2 / 1000)
);
expect(differingFraction(plain, squared)).toBeGreaterThan(0.05);
});
});
10 changes: 10 additions & 0 deletions tests/specs/volumeTestUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ export function floatVoxels(size: number, valueAt: (index: number) => number) {
return buffer;
}

/** 1000 at the cube center, falling linearly to 0 at half the edge length. */
export const radialRamp = (size: number) => (index: number) => {
const offsets = [
index % size,
Math.floor(index / size) % size,
Math.floor(index / size ** 2),
].map((c) => c - size / 2);
return Math.max(0, 1000 * (1 - Math.hypot(...offsets) / (size / 2)));
};

export function writeNrrd(name: string, header: string, voxels: Buffer) {
const directory = makeTempDir(name);
fs.writeFileSync(
Expand Down
Loading