-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathimage-stats.ts
More file actions
260 lines (225 loc) · 7.01 KB
/
image-stats.ts
File metadata and controls
260 lines (225 loc) · 7.01 KB
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
254
255
256
257
258
259
260
import { defineStore } from 'pinia';
import {
reactive,
watch,
computed,
MaybeRef,
unref,
effectScope,
type EffectScope,
} from 'vue';
import * as Comlink from 'comlink';
import vtkDataArray from '@kitware/vtk.js/Common/Core/DataArray';
import vtkImageData from '@kitware/vtk.js/Common/DataModel/ImageData';
import { useVtkComputed } from '@/src/core/vtk/useVtkComputed';
import { WLAutoRanges, WL_HIST_BINS } from '@/src/constants';
import { HistogramWorker } from '@/src/utils/histogram.worker';
import { Maybe } from '@/src/types';
import { useImage } from '@/src/composables/useCurrentImage';
import { ensureError } from '@/src/utils';
import { useImageCacheStore } from './image-cache';
import { useMessageStore } from './messages';
export type ImageStats = {
scalarMin: number;
scalarMax: number;
autoRangeValues?: Record<string, [number, number]>;
};
function getRangesWithCache(scalars: vtkDataArray) {
const numberOfComponents = scalars.getNumberOfComponents();
return Array.from({ length: numberOfComponents }, (_, i) => {
const [min, max] = scalars.getRange(i);
return { min, max };
});
}
function getAllComponentRange(scalars: vtkDataArray) {
const ranges = getRangesWithCache(scalars);
const min = ranges
.map((range) => range.min)
.reduce((acc, val) => Math.min(acc, val), Infinity);
const max = ranges
.map((range) => range.max)
.reduce((acc, val) => Math.max(acc, val), -Infinity);
return { min, max };
}
async function computeAutoRangeValues(imageData: vtkImageData) {
const scalars = imageData.getPointData()?.getScalars();
if (!scalars) {
return {};
}
const worker = Comlink.wrap<HistogramWorker>(
new Worker(new URL('@/src/utils/histogram.worker.ts', import.meta.url), {
type: 'module',
})
);
const { min, max } = getAllComponentRange(scalars);
const scalarData = scalars.getData() as number[];
const hist = await worker.histogram(scalarData, [min, max], WL_HIST_BINS);
worker[Comlink.releaseProxy]();
const cumulativeHist: number[] = [];
hist.reduce((acc, val) => {
const currentSum = acc + val;
cumulativeHist.push(currentSum);
return currentSum;
}, 0);
const width = (max - min + 1) / WL_HIST_BINS;
const totalCount = scalarData.length;
return Object.fromEntries(
Object.entries(WLAutoRanges).map(([key, percentage]) => {
const lowerBound = percentage * 0.01 * totalCount;
const upperBound = (1 - percentage * 0.01) * totalCount;
const startIdx = cumulativeHist.findIndex((v) => v >= lowerBound);
const endIdx = cumulativeHist.findIndex((v) => v >= upperBound);
const start = Math.max(min, min + width * startIdx);
const end = Math.min(max, min + width * (endIdx + 1)); // Adjusted end calculation
return [key, [start, end] as [number, number]];
})
);
}
export const useImageStatsStore = defineStore('image-stats', () => {
const stats = reactive<Record<string, ImageStats>>({});
const imageCacheStore = useImageCacheStore();
const messageStore = useMessageStore();
const statsEffectScope: Record<string, EffectScope> = {};
const autoRangeComputations: Record<
string,
Promise<Record<string, [number, number]>>
> = {};
const internalSetScalarRange = (
imageID: string,
min: number,
max: number
) => {
stats[imageID] = {
...stats[imageID],
scalarMin: min,
scalarMax: max,
};
};
const internalSetAutoRangeValues = (
imageID: string,
autoValues: Record<string, [number, number]>
) => {
stats[imageID] = {
...stats[imageID],
autoRangeValues: autoValues,
};
};
const internalRemoveStats = (imageID: string) => {
delete stats[imageID];
};
const setupImageWatchers = (id: string) => {
const { imageData, isLoading: isImageLoading } = useImage(
computed(() => id)
);
const activeScalars = computed(() =>
imageData.value?.getPointData()?.getScalars()
);
// useVtkComputed listens to VTK onModified events for progressive range updates
const scalarRange = useVtkComputed(activeScalars, () =>
activeScalars.value?.getRange(0)
);
watch(
scalarRange,
(range) => {
if (range) {
internalSetScalarRange(id, range[0], range[1]);
}
},
{ immediate: true }
);
// Watch activeScalars directly to handle when entire scalars object is replaced
// (e.g., SEG DICOM images that replace vtkImageData after loading)
watch(activeScalars, (scalars) => {
if (!scalars) return;
const range = scalars.getRange(0);
if (range) {
internalSetScalarRange(id, range[0], range[1]);
}
});
const triggerAutoRangeComputation = (image: vtkImageData) => {
autoRangeComputations[id] = computeAutoRangeValues(image);
autoRangeComputations[id]
.then((autoValues) => {
if (imageCacheStore.imageIds.includes(id)) {
// not deleted yet, save values
internalSetAutoRangeValues(id, autoValues);
}
})
.catch((error) => {
console.error(
`[ImageStatsStore] Auto range computation for image ${id} FAILED:`,
error
);
messageStore.addError(
`Auto range computation failed for image ${id}`,
{ error: ensureError(error) }
);
})
.finally(() => {
delete autoRangeComputations[id];
});
};
watch(
[imageData, isImageLoading],
() => {
if (
isImageLoading.value ||
!imageData.value ||
id in autoRangeComputations ||
(stats[id] && stats[id].autoRangeValues)
)
return;
triggerAutoRangeComputation(imageData.value);
},
{ immediate: true }
);
};
const cleanupImage = (id: string) => {
internalRemoveStats(id);
if (statsEffectScope[id]) {
statsEffectScope[id].stop();
delete statsEffectScope[id];
}
if (id in autoRangeComputations) {
delete autoRangeComputations[id];
}
};
watch(
() => [...imageCacheStore.imageIds],
(currentImageIds, previousImageIds = []) => {
const addedIds = currentImageIds.filter(
(id) => !previousImageIds.includes(id)
);
const removedIds = previousImageIds.filter(
(id) => !currentImageIds.includes(id)
);
removedIds.forEach(cleanupImage);
addedIds.forEach((id) => {
if (statsEffectScope[id]) {
cleanupImage(id);
console.error(`Setting up stats for ${id} twice!`);
}
statsEffectScope[id] = effectScope();
statsEffectScope[id].run(() => {
setupImageWatchers(id);
});
});
},
{ immediate: true }
);
const getAutoRangeValues = (imageID: MaybeRef<Maybe<string>>) => {
const id = unref(imageID);
if (id && stats[id]) {
return stats[id].autoRangeValues ?? {};
}
return {};
};
const removeData = (id: string) => {
delete stats[id];
};
return {
stats,
getAutoRangeValues,
removeData,
};
});