@fideus-labs/ngff-zarr 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +1 -0
  2. package/esm/browser-mod.d.ts +14 -0
  3. package/esm/browser-mod.d.ts.map +1 -0
  4. package/esm/browser-mod.js +23 -0
  5. package/esm/io/itk_image_to_ngff_image.d.ts +5 -0
  6. package/esm/io/itk_image_to_ngff_image.d.ts.map +1 -1
  7. package/esm/io/itk_image_to_ngff_image.js +20 -20
  8. package/esm/io/ngff_image_to_itk_image.d.ts.map +1 -1
  9. package/esm/io/ngff_image_to_itk_image.js +2 -0
  10. package/esm/io/to_multiscales.js +1 -1
  11. package/esm/io/to_ngff_zarr.js +16 -0
  12. package/esm/methods/itkwasm-browser.d.ts +6 -0
  13. package/esm/methods/itkwasm-browser.d.ts.map +1 -0
  14. package/esm/methods/itkwasm-browser.js +462 -0
  15. package/esm/methods/itkwasm-node.d.ts +6 -0
  16. package/esm/methods/itkwasm-node.d.ts.map +1 -0
  17. package/esm/methods/itkwasm-node.js +462 -0
  18. package/esm/methods/itkwasm-shared.d.ts +68 -0
  19. package/esm/methods/itkwasm-shared.d.ts.map +1 -0
  20. package/esm/methods/itkwasm-shared.js +489 -0
  21. package/esm/methods/itkwasm.d.ts +11 -3
  22. package/esm/methods/itkwasm.d.ts.map +1 -1
  23. package/esm/methods/itkwasm.js +11 -810
  24. package/esm/schemas/coordinate_systems.d.ts +159 -552
  25. package/esm/schemas/coordinate_systems.d.ts.map +1 -1
  26. package/esm/schemas/coordinate_systems.js +0 -1
  27. package/esm/schemas/ome_zarr.d.ts +105 -69
  28. package/esm/schemas/ome_zarr.d.ts.map +1 -1
  29. package/esm/schemas/rfc4.d.ts +26 -131
  30. package/esm/schemas/rfc4.d.ts.map +1 -1
  31. package/esm/schemas/units.d.ts +70 -5
  32. package/esm/schemas/units.d.ts.map +1 -1
  33. package/esm/schemas/units.js +2 -15
  34. package/esm/schemas/zarr_metadata.d.ts +13 -300
  35. package/esm/schemas/zarr_metadata.d.ts.map +1 -1
  36. package/package.json +27 -3
  37. package/script/browser-mod.d.ts +14 -0
  38. package/script/browser-mod.d.ts.map +1 -0
  39. package/script/browser-mod.js +48 -0
  40. package/script/io/itk_image_to_ngff_image.d.ts +5 -0
  41. package/script/io/itk_image_to_ngff_image.d.ts.map +1 -1
  42. package/script/io/itk_image_to_ngff_image.js +20 -20
  43. package/script/io/ngff_image_to_itk_image.d.ts.map +1 -1
  44. package/script/io/ngff_image_to_itk_image.js +2 -0
  45. package/script/io/to_multiscales.js +1 -1
  46. package/script/io/to_ngff_zarr.js +16 -0
  47. package/script/methods/itkwasm-browser.d.ts +6 -0
  48. package/script/methods/itkwasm-browser.d.ts.map +1 -0
  49. package/script/methods/itkwasm-browser.js +488 -0
  50. package/script/methods/itkwasm-node.d.ts +6 -0
  51. package/script/methods/itkwasm-node.d.ts.map +1 -0
  52. package/script/methods/itkwasm-node.js +488 -0
  53. package/script/methods/itkwasm-shared.d.ts +68 -0
  54. package/script/methods/itkwasm-shared.d.ts.map +1 -0
  55. package/script/methods/itkwasm-shared.js +524 -0
  56. package/script/methods/itkwasm.d.ts +11 -3
  57. package/script/methods/itkwasm.d.ts.map +1 -1
  58. package/script/methods/itkwasm.js +14 -835
  59. package/script/schemas/coordinate_systems.d.ts +159 -552
  60. package/script/schemas/coordinate_systems.d.ts.map +1 -1
  61. package/script/schemas/coordinate_systems.js +0 -1
  62. package/script/schemas/ome_zarr.d.ts +105 -69
  63. package/script/schemas/ome_zarr.d.ts.map +1 -1
  64. package/script/schemas/rfc4.d.ts +26 -131
  65. package/script/schemas/rfc4.d.ts.map +1 -1
  66. package/script/schemas/units.d.ts +70 -5
  67. package/script/schemas/units.d.ts.map +1 -1
  68. package/script/schemas/units.js +2 -15
  69. package/script/schemas/zarr_metadata.d.ts +13 -300
  70. package/script/schemas/zarr_metadata.d.ts.map +1 -1
@@ -0,0 +1,488 @@
1
+ "use strict";
2
+ // SPDX-FileCopyrightText: Copyright (c) Fideus Labs LLC
3
+ // SPDX-License-Identifier: MIT
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
19
+ });
20
+ var __importStar = (this && this.__importStar) || function (mod) {
21
+ if (mod && mod.__esModule) return mod;
22
+ var result = {};
23
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
+ __setModuleDefault(result, mod);
25
+ return result;
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.downsampleItkWasm = downsampleItkWasm;
29
+ /**
30
+ * Node-compatible ITK-Wasm downsampling support
31
+ * Uses native WASM implementations from @itk-wasm/downsample
32
+ */
33
+ const downsample_1 = require("@itk-wasm/downsample");
34
+ const zarr = __importStar(require("zarrita"));
35
+ const ngff_image_js_1 = require("../types/ngff_image.js");
36
+ const itkwasm_shared_js_1 = require("./itkwasm-shared.js");
37
+ /**
38
+ * Perform Gaussian downsampling using ITK-Wasm (browser version)
39
+ */
40
+ async function downsampleGaussian(image, dimFactors, spatialDims) {
41
+ // Handle time dimension by processing each time slice independently
42
+ if (image.dims.includes("t")) {
43
+ const tDimIndex = image.dims.indexOf("t");
44
+ const tSize = image.data.shape[tDimIndex];
45
+ const newDims = image.dims.filter((dim) => dim !== "t");
46
+ // Downsample each time slice
47
+ const downsampledSlices = [];
48
+ for (let t = 0; t < tSize; t++) {
49
+ // Extract time slice
50
+ const selection = new Array(image.data.shape.length).fill(null);
51
+ selection[tDimIndex] = t;
52
+ const sliceData = await zarr.get(image.data, selection);
53
+ // Create temporary zarr array for this slice
54
+ const sliceStore = new Map();
55
+ const sliceRoot = zarr.root(sliceStore);
56
+ const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
57
+ const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
58
+ const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
59
+ shape: sliceShape,
60
+ chunk_shape: sliceChunkShape,
61
+ data_type: image.data.dtype,
62
+ fill_value: 0,
63
+ });
64
+ const fullSelection = new Array(sliceShape.length).fill(null);
65
+ await zarr.set(sliceArray, fullSelection, sliceData);
66
+ // Create NgffImage for this slice (without 't' dimension)
67
+ const sliceImage = new ngff_image_js_1.NgffImage({
68
+ data: sliceArray,
69
+ dims: newDims,
70
+ scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
71
+ translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
72
+ name: image.name,
73
+ axesUnits: image.axesUnits
74
+ ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
75
+ : undefined,
76
+ computedCallbacks: image.computedCallbacks,
77
+ });
78
+ // Recursively downsample this slice (without 't', so no infinite loop)
79
+ const downsampledSlice = await downsampleGaussian(sliceImage, dimFactors, spatialDims);
80
+ downsampledSlices.push(downsampledSlice.data);
81
+ }
82
+ // Combine downsampled slices back into a single array with 't' dimension
83
+ const firstSlice = downsampledSlices[0];
84
+ const combinedShape = [...image.data.shape];
85
+ combinedShape[tDimIndex] = tSize;
86
+ // Update spatial dimensions based on downsampled size
87
+ for (let i = 0; i < image.dims.length; i++) {
88
+ if (i !== tDimIndex) {
89
+ const sliceIndex = i < tDimIndex ? i : i - 1;
90
+ combinedShape[i] = firstSlice.shape[sliceIndex];
91
+ }
92
+ }
93
+ // Create combined array
94
+ const combinedStore = new Map();
95
+ const combinedRoot = zarr.root(combinedStore);
96
+ const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
97
+ shape: combinedShape,
98
+ chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
99
+ data_type: image.data.dtype,
100
+ fill_value: 0,
101
+ });
102
+ // Copy each downsampled slice into the combined array
103
+ for (let t = 0; t < tSize; t++) {
104
+ const sliceData = await zarr.get(downsampledSlices[t]);
105
+ const targetSelection = new Array(combinedShape.length).fill(null);
106
+ targetSelection[tDimIndex] = t;
107
+ await zarr.set(combinedArray, targetSelection, sliceData);
108
+ }
109
+ // Compute new metadata (time dimension unchanged, spatial dimensions downsampled)
110
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
111
+ return new ngff_image_js_1.NgffImage({
112
+ data: combinedArray,
113
+ dims: image.dims,
114
+ scale: { ...image.scale, ...scale },
115
+ translation: { ...image.translation, ...translation },
116
+ name: image.name,
117
+ axesUnits: image.axesUnits,
118
+ computedCallbacks: image.computedCallbacks,
119
+ });
120
+ }
121
+ const isVector = image.dims.includes("c");
122
+ // Convert to ITK-Wasm format
123
+ const itkImage = await (0, itkwasm_shared_js_1.zarrToItkImage)(image.data, image.dims, isVector);
124
+ // Prepare shrink factors - need to be for ALL dimensions in ITK order (reversed)
125
+ const shrinkFactors = [];
126
+ for (let i = image.dims.length - 1; i >= 0; i--) {
127
+ const dim = image.dims[i];
128
+ if (itkwasm_shared_js_1.SPATIAL_DIMS.includes(dim)) {
129
+ shrinkFactors.push(dimFactors[dim] || 1);
130
+ }
131
+ }
132
+ // Use all zeros for cropRadius
133
+ const cropRadius = new Array(shrinkFactors.length).fill(0);
134
+ // Perform downsampling using browser-compatible function
135
+ const { downsampled } = await (0, downsample_1.downsampleNode)(itkImage, {
136
+ shrinkFactors,
137
+ cropRadius: cropRadius,
138
+ });
139
+ // Compute new metadata
140
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
141
+ // Convert back to zarr array in a new in-memory store
142
+ const store = new Map();
143
+ const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
144
+ const array = await (0, itkwasm_shared_js_1.itkImageToZarr)(downsampled, store, "image", chunkShape, image.dims);
145
+ return new ngff_image_js_1.NgffImage({
146
+ data: array,
147
+ dims: image.dims,
148
+ scale,
149
+ translation,
150
+ name: image.name,
151
+ axesUnits: image.axesUnits,
152
+ computedCallbacks: image.computedCallbacks,
153
+ });
154
+ }
155
+ /**
156
+ * Perform bin shrink downsampling using ITK-Wasm (browser version)
157
+ */
158
+ async function downsampleBinShrinkImpl(image, dimFactors, spatialDims) {
159
+ // Handle time dimension by processing each time slice independently
160
+ if (image.dims.includes("t")) {
161
+ const tDimIndex = image.dims.indexOf("t");
162
+ const tSize = image.data.shape[tDimIndex];
163
+ const newDims = image.dims.filter((dim) => dim !== "t");
164
+ // Downsample each time slice
165
+ const downsampledSlices = [];
166
+ for (let t = 0; t < tSize; t++) {
167
+ // Extract time slice
168
+ const selection = new Array(image.data.shape.length).fill(null);
169
+ selection[tDimIndex] = t;
170
+ const sliceData = await zarr.get(image.data, selection);
171
+ // Create temporary zarr array for this slice
172
+ const sliceStore = new Map();
173
+ const sliceRoot = zarr.root(sliceStore);
174
+ const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
175
+ const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
176
+ const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
177
+ shape: sliceShape,
178
+ chunk_shape: sliceChunkShape,
179
+ data_type: image.data.dtype,
180
+ fill_value: 0,
181
+ });
182
+ const fullSelection = new Array(sliceShape.length).fill(null);
183
+ await zarr.set(sliceArray, fullSelection, sliceData);
184
+ // Create NgffImage for this slice (without 't' dimension)
185
+ const sliceImage = new ngff_image_js_1.NgffImage({
186
+ data: sliceArray,
187
+ dims: newDims,
188
+ scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
189
+ translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
190
+ name: image.name,
191
+ axesUnits: image.axesUnits
192
+ ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
193
+ : undefined,
194
+ computedCallbacks: image.computedCallbacks,
195
+ });
196
+ // Recursively downsample this slice
197
+ const downsampledSlice = await downsampleBinShrinkImpl(sliceImage, dimFactors, spatialDims);
198
+ downsampledSlices.push(downsampledSlice.data);
199
+ }
200
+ // Combine downsampled slices back into a single array with 't' dimension
201
+ const firstSlice = downsampledSlices[0];
202
+ const combinedShape = [...image.data.shape];
203
+ combinedShape[tDimIndex] = tSize;
204
+ // Update spatial dimensions based on downsampled size
205
+ for (let i = 0; i < image.dims.length; i++) {
206
+ if (i !== tDimIndex) {
207
+ const sliceIndex = i < tDimIndex ? i : i - 1;
208
+ combinedShape[i] = firstSlice.shape[sliceIndex];
209
+ }
210
+ }
211
+ // Create combined array
212
+ const combinedStore = new Map();
213
+ const combinedRoot = zarr.root(combinedStore);
214
+ const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
215
+ shape: combinedShape,
216
+ chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
217
+ data_type: image.data.dtype,
218
+ fill_value: 0,
219
+ });
220
+ // Copy each downsampled slice into the combined array
221
+ for (let t = 0; t < tSize; t++) {
222
+ const sliceData = await zarr.get(downsampledSlices[t]);
223
+ const targetSelection = new Array(combinedShape.length).fill(null);
224
+ targetSelection[tDimIndex] = t;
225
+ await zarr.set(combinedArray, targetSelection, sliceData);
226
+ }
227
+ // Compute new metadata
228
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
229
+ return new ngff_image_js_1.NgffImage({
230
+ data: combinedArray,
231
+ dims: image.dims,
232
+ scale: { ...image.scale, ...scale },
233
+ translation: { ...image.translation, ...translation },
234
+ name: image.name,
235
+ axesUnits: image.axesUnits,
236
+ computedCallbacks: image.computedCallbacks,
237
+ });
238
+ }
239
+ const isVector = image.dims.includes("c");
240
+ // Convert to ITK-Wasm format
241
+ const itkImage = await (0, itkwasm_shared_js_1.zarrToItkImage)(image.data, image.dims, isVector);
242
+ // Prepare shrink factors - only for spatial dimensions in ITK order (reversed)
243
+ const shrinkFactors = [];
244
+ for (let i = image.dims.length - 1; i >= 0; i--) {
245
+ const dim = image.dims[i];
246
+ if (itkwasm_shared_js_1.SPATIAL_DIMS.includes(dim)) {
247
+ shrinkFactors.push(dimFactors[dim] || 1);
248
+ }
249
+ }
250
+ // Perform downsampling using browser-compatible function
251
+ const { downsampled } = await (0, downsample_1.downsampleBinShrinkNode)(itkImage, {
252
+ shrinkFactors,
253
+ });
254
+ // Compute new metadata
255
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
256
+ // Convert back to zarr array in a new in-memory store
257
+ const store = new Map();
258
+ const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
259
+ const array = await (0, itkwasm_shared_js_1.itkImageToZarr)(downsampled, store, "image", chunkShape, image.dims);
260
+ return new ngff_image_js_1.NgffImage({
261
+ data: array,
262
+ dims: image.dims,
263
+ scale,
264
+ translation,
265
+ name: image.name,
266
+ axesUnits: image.axesUnits,
267
+ computedCallbacks: image.computedCallbacks,
268
+ });
269
+ }
270
+ /**
271
+ * Perform label image downsampling using ITK-Wasm (browser version)
272
+ */
273
+ async function downsampleLabelImageImpl(image, dimFactors, spatialDims) {
274
+ // Handle time dimension by processing each time slice independently
275
+ if (image.dims.includes("t")) {
276
+ const tDimIndex = image.dims.indexOf("t");
277
+ const tSize = image.data.shape[tDimIndex];
278
+ const newDims = image.dims.filter((dim) => dim !== "t");
279
+ // Downsample each time slice
280
+ const downsampledSlices = [];
281
+ for (let t = 0; t < tSize; t++) {
282
+ // Extract time slice
283
+ const selection = new Array(image.data.shape.length).fill(null);
284
+ selection[tDimIndex] = t;
285
+ const sliceData = await zarr.get(image.data, selection);
286
+ // Create temporary zarr array for this slice
287
+ const sliceStore = new Map();
288
+ const sliceRoot = zarr.root(sliceStore);
289
+ const sliceShape = image.data.shape.filter((_, i) => i !== tDimIndex);
290
+ const sliceChunkShape = sliceShape.map((s) => Math.min(s, 256));
291
+ const sliceArray = await zarr.create(sliceRoot.resolve("slice"), {
292
+ shape: sliceShape,
293
+ chunk_shape: sliceChunkShape,
294
+ data_type: image.data.dtype,
295
+ fill_value: 0,
296
+ });
297
+ const fullSelection = new Array(sliceShape.length).fill(null);
298
+ await zarr.set(sliceArray, fullSelection, sliceData);
299
+ // Create NgffImage for this slice (without 't' dimension)
300
+ const sliceImage = new ngff_image_js_1.NgffImage({
301
+ data: sliceArray,
302
+ dims: newDims,
303
+ scale: Object.fromEntries(Object.entries(image.scale).filter(([dim]) => dim !== "t")),
304
+ translation: Object.fromEntries(Object.entries(image.translation).filter(([dim]) => dim !== "t")),
305
+ name: image.name,
306
+ axesUnits: image.axesUnits
307
+ ? Object.fromEntries(Object.entries(image.axesUnits).filter(([dim]) => dim !== "t"))
308
+ : undefined,
309
+ computedCallbacks: image.computedCallbacks,
310
+ });
311
+ // Recursively downsample this slice
312
+ const downsampledSlice = await downsampleLabelImageImpl(sliceImage, dimFactors, spatialDims);
313
+ downsampledSlices.push(downsampledSlice.data);
314
+ }
315
+ // Combine downsampled slices back into a single array with 't' dimension
316
+ const firstSlice = downsampledSlices[0];
317
+ const combinedShape = [...image.data.shape];
318
+ combinedShape[tDimIndex] = tSize;
319
+ // Update spatial dimensions based on downsampled size
320
+ for (let i = 0; i < image.dims.length; i++) {
321
+ if (i !== tDimIndex) {
322
+ const sliceIndex = i < tDimIndex ? i : i - 1;
323
+ combinedShape[i] = firstSlice.shape[sliceIndex];
324
+ }
325
+ }
326
+ // Create combined array
327
+ const combinedStore = new Map();
328
+ const combinedRoot = zarr.root(combinedStore);
329
+ const combinedArray = await zarr.create(combinedRoot.resolve("combined"), {
330
+ shape: combinedShape,
331
+ chunk_shape: combinedShape.map((s) => Math.min(s, 256)),
332
+ data_type: image.data.dtype,
333
+ fill_value: 0,
334
+ });
335
+ // Copy each downsampled slice into the combined array
336
+ for (let t = 0; t < tSize; t++) {
337
+ const sliceData = await zarr.get(downsampledSlices[t]);
338
+ const targetSelection = new Array(combinedShape.length).fill(null);
339
+ targetSelection[tDimIndex] = t;
340
+ await zarr.set(combinedArray, targetSelection, sliceData);
341
+ }
342
+ // Compute new metadata
343
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
344
+ return new ngff_image_js_1.NgffImage({
345
+ data: combinedArray,
346
+ dims: image.dims,
347
+ scale: { ...image.scale, ...scale },
348
+ translation: { ...image.translation, ...translation },
349
+ name: image.name,
350
+ axesUnits: image.axesUnits,
351
+ computedCallbacks: image.computedCallbacks,
352
+ });
353
+ }
354
+ const isVector = image.dims.includes("c");
355
+ // Convert to ITK-Wasm format
356
+ const itkImage = await (0, itkwasm_shared_js_1.zarrToItkImage)(image.data, image.dims, isVector);
357
+ // Prepare shrink factors - need to be for ALL dimensions in ITK order (reversed)
358
+ const shrinkFactors = [];
359
+ for (let i = image.dims.length - 1; i >= 0; i--) {
360
+ const dim = image.dims[i];
361
+ if (itkwasm_shared_js_1.SPATIAL_DIMS.includes(dim)) {
362
+ shrinkFactors.push(dimFactors[dim] || 1);
363
+ }
364
+ else {
365
+ shrinkFactors.push(1); // Non-spatial dimensions don't shrink
366
+ }
367
+ }
368
+ // Use all zeros for cropRadius
369
+ const cropRadius = new Array(shrinkFactors.length).fill(0);
370
+ // Perform downsampling using browser-compatible function
371
+ const { downsampled } = await (0, downsample_1.downsampleLabelImageNode)(itkImage, {
372
+ shrinkFactors,
373
+ cropRadius: cropRadius,
374
+ });
375
+ // Compute new metadata
376
+ const [translation, scale] = (0, itkwasm_shared_js_1.nextScaleMetadata)(image, dimFactors, spatialDims);
377
+ // Convert back to zarr array in a new in-memory store
378
+ const store = new Map();
379
+ const chunkShape = downsampled.size.map((s) => Math.min(s, 256)).reverse();
380
+ const array = await (0, itkwasm_shared_js_1.itkImageToZarr)(downsampled, store, "image", chunkShape, image.dims);
381
+ return new ngff_image_js_1.NgffImage({
382
+ data: array,
383
+ dims: image.dims,
384
+ scale,
385
+ translation,
386
+ name: image.name,
387
+ axesUnits: image.axesUnits,
388
+ computedCallbacks: image.computedCallbacks,
389
+ });
390
+ }
391
+ /**
392
+ * Main downsampling function for ITK-Wasm (browser version)
393
+ */
394
+ async function downsampleItkWasm(ngffImage, scaleFactors, smoothing) {
395
+ const multiscales = [ngffImage];
396
+ const dims = ngffImage.dims;
397
+ const spatialDims = dims.filter((dim) => itkwasm_shared_js_1.SPATIAL_DIMS.includes(dim));
398
+ let previousImage = ngffImage;
399
+ let previousDimFactors = {};
400
+ for (const dim of dims)
401
+ previousDimFactors[dim] = 1;
402
+ for (let i = 0; i < scaleFactors.length; i++) {
403
+ const scaleFactor = scaleFactors[i];
404
+ let sourceImage;
405
+ let sourceDimFactors;
406
+ if (smoothing === "bin_shrink") {
407
+ // Purely incremental: scaleFactor is the shrink for this step
408
+ sourceImage = previousImage;
409
+ sourceDimFactors = {};
410
+ if (typeof scaleFactor === "number") {
411
+ for (const dim of spatialDims)
412
+ sourceDimFactors[dim] = scaleFactor;
413
+ }
414
+ else {
415
+ for (const dim of spatialDims) {
416
+ sourceDimFactors[dim] = scaleFactor[dim] || 1;
417
+ }
418
+ }
419
+ for (const dim of dims) {
420
+ if (!(dim in sourceDimFactors))
421
+ sourceDimFactors[dim] = 1;
422
+ }
423
+ }
424
+ else {
425
+ // Hybrid absolute strategy
426
+ const dimFactors = (0, itkwasm_shared_js_1.dimScaleFactors)(dims, scaleFactor, previousDimFactors, ngffImage, previousImage);
427
+ let canDownsampleIncrementally = true;
428
+ for (const dim of Object.keys(dimFactors)) {
429
+ const dimIndex = ngffImage.dims.indexOf(dim);
430
+ if (dimIndex >= 0) {
431
+ const originalSize = ngffImage.data.shape[dimIndex];
432
+ const targetSize = Math.floor(originalSize /
433
+ (typeof scaleFactor === "number"
434
+ ? scaleFactor
435
+ : scaleFactor[dim]));
436
+ const prevDimIndex = previousImage.dims.indexOf(dim);
437
+ const previousSize = previousImage.data.shape[prevDimIndex];
438
+ if (Math.floor(previousSize / dimFactors[dim]) !== targetSize) {
439
+ canDownsampleIncrementally = false;
440
+ break;
441
+ }
442
+ }
443
+ }
444
+ if (canDownsampleIncrementally) {
445
+ sourceImage = previousImage;
446
+ sourceDimFactors = dimFactors;
447
+ }
448
+ else {
449
+ sourceImage = ngffImage;
450
+ const originalDimFactors = {};
451
+ for (const dim of dims)
452
+ originalDimFactors[dim] = 1;
453
+ sourceDimFactors = (0, itkwasm_shared_js_1.dimScaleFactors)(dims, scaleFactor, originalDimFactors);
454
+ }
455
+ }
456
+ let downsampled;
457
+ if (smoothing === "gaussian") {
458
+ downsampled = await downsampleGaussian(sourceImage, sourceDimFactors, spatialDims);
459
+ }
460
+ else if (smoothing === "bin_shrink") {
461
+ downsampled = await downsampleBinShrinkImpl(sourceImage, sourceDimFactors, spatialDims);
462
+ }
463
+ else if (smoothing === "label_image") {
464
+ downsampled = await downsampleLabelImageImpl(sourceImage, sourceDimFactors, spatialDims);
465
+ }
466
+ else {
467
+ throw new Error(`Unknown smoothing method: ${smoothing}`);
468
+ }
469
+ multiscales.push(downsampled);
470
+ previousImage = downsampled;
471
+ if (smoothing === "bin_shrink") {
472
+ if (typeof scaleFactor === "number") {
473
+ for (const dim of spatialDims) {
474
+ previousDimFactors[dim] *= scaleFactor;
475
+ }
476
+ }
477
+ else {
478
+ for (const dim of spatialDims) {
479
+ previousDimFactors[dim] *= scaleFactor[dim] || 1;
480
+ }
481
+ }
482
+ }
483
+ else {
484
+ previousDimFactors = (0, itkwasm_shared_js_1.updatePreviousDimFactors)(scaleFactor, spatialDims, previousDimFactors);
485
+ }
486
+ }
487
+ return multiscales;
488
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Shared helper functions for ITK-Wasm downsampling
3
+ * Used by both browser and Node implementations
4
+ */
5
+ import type { Image } from "itk-wasm";
6
+ import * as zarr from "zarrita";
7
+ import { NgffImage } from "../types/ngff_image.js";
8
+ export declare const SPATIAL_DIMS: string[];
9
+ export interface DimFactors {
10
+ [key: string]: number;
11
+ }
12
+ /**
13
+ * Calculate the incremental factor needed to reach the target size from the previous size.
14
+ * This ensures exact target sizes when downsampling incrementally.
15
+ */
16
+ export declare function calculateIncrementalFactor(previousSize: number, targetSize: number): number;
17
+ /**
18
+ * Convert dimension scale factors to ITK-Wasm format
19
+ * This computes the incremental scale factor relative to the previous scale,
20
+ * not the absolute scale factor from the original image.
21
+ *
22
+ * When originalImage and previousImage are provided, calculates the exact
23
+ * incremental factor needed to reach the target size from the previous size.
24
+ * This ensures we get exact 1x, 2x, 3x, 4x sizes even with incremental downsampling.
25
+ */
26
+ export declare function dimScaleFactors(dims: string[], scaleFactor: Record<string, number> | number, previousDimFactors: DimFactors, originalImage?: NgffImage, previousImage?: NgffImage): DimFactors;
27
+ /**
28
+ * Update previous dimension factors
29
+ */
30
+ export declare function updatePreviousDimFactors(scaleFactor: Record<string, number> | number, spatialDims: string[], previousDimFactors: DimFactors): DimFactors;
31
+ /**
32
+ * Compute next scale metadata
33
+ */
34
+ export declare function nextScaleMetadata(image: NgffImage, dimFactors: DimFactors, spatialDims: string[]): [Record<string, number>, Record<string, number>];
35
+ /**
36
+ * Get ITK component type from typed array
37
+ */
38
+ export declare function getItkComponentType(data: unknown): "uint8" | "int8" | "uint16" | "int16" | "uint32" | "int32" | "float32" | "float64";
39
+ /**
40
+ * Create identity matrix for ITK direction
41
+ */
42
+ export declare function createIdentityMatrix(dimension: number): Float64Array;
43
+ /**
44
+ * Transpose array data according to permutation
45
+ */
46
+ export declare function transposeArray(data: unknown, shape: number[], permutation: number[], componentType: "uint8" | "int8" | "uint16" | "int16" | "uint32" | "int32" | "float32" | "float64"): Float32Array | Float64Array | Uint8Array | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
47
+ /**
48
+ * Convert zarr array to ITK-Wasm Image format
49
+ * If isVector is true, ensures "c" dimension is last by transposing if needed
50
+ */
51
+ export declare function zarrToItkImage(array: zarr.Array<zarr.DataType, zarr.Readable>, dims: string[], isVector?: boolean): Promise<Image>;
52
+ /**
53
+ * Convert ITK-Wasm Image back to zarr array
54
+ * Uses the provided store instead of creating a new one
55
+ *
56
+ * Important: ITK-Wasm stores size in physical space order [x, y, z], but data in
57
+ * column-major order (x contiguous). This column-major layout with size [x, y, z]
58
+ * is equivalent to C-order (row-major) with shape [z, y, x]. We reverse the size
59
+ * to get the zarr shape and use C-order strides for that reversed shape.
60
+ *
61
+ * @param itkImage - The ITK-Wasm image to convert
62
+ * @param store - The zarr store to write to
63
+ * @param path - The path within the store
64
+ * @param chunkShape - The chunk shape (in spatial dimension order, will be adjusted for components)
65
+ * @param targetDims - The target dimension order (e.g., ["c", "z", "y", "x"])
66
+ */
67
+ export declare function itkImageToZarr(itkImage: Image, store: Map<string, Uint8Array>, path: string, chunkShape: number[], targetDims?: string[]): Promise<zarr.Array<zarr.DataType, zarr.Readable>>;
68
+ //# sourceMappingURL=itkwasm-shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"itkwasm-shared.d.ts","sourceRoot":"","sources":["../../src/methods/itkwasm-shared.ts"],"names":[],"mappings":"AAGA;;;GAGG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,SAAS,CAAC;AAChC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD,eAAO,MAAM,YAAY,UAAkB,CAAC;AAE5C,MAAM,WAAW,UAAU;IACzB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CACvB;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,GACjB,MAAM,CAsBR;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,MAAM,EAAE,EACd,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,EAC5C,kBAAkB,EAAE,UAAU,EAC9B,aAAa,CAAC,EAAE,SAAS,EACzB,aAAa,CAAC,EAAE,SAAS,GACxB,UAAU,CAqEZ;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CACtC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,EAC5C,WAAW,EAAE,MAAM,EAAE,EACrB,kBAAkB,EAAE,UAAU,GAC7B,UAAU,CAcZ;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,SAAS,EAChB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,MAAM,EAAE,GACpB,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAkBlD;AAsCD;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,OAAO,GAEX,OAAO,GACP,MAAM,GACN,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,OAAO,GACP,SAAS,GACT,SAAS,CASZ;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,GAAG,YAAY,CAMpE;AAcD;;GAEG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,OAAO,EACb,KAAK,EAAE,MAAM,EAAE,EACf,WAAW,EAAE,MAAM,EAAE,EACrB,aAAa,EACT,OAAO,GACP,MAAM,GACN,QAAQ,GACR,OAAO,GACP,QAAQ,GACR,OAAO,GACP,SAAS,GACT,SAAS,GAEX,YAAY,GACZ,YAAY,GACZ,UAAU,GACV,SAAS,GACT,WAAW,GACX,UAAU,GACV,WAAW,GACX,UAAU,CAqFb;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EAC/C,IAAI,EAAE,MAAM,EAAE,EACd,QAAQ,UAAQ,GACf,OAAO,CAAC,KAAK,CAAC,CAqFhB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,KAAK,EACf,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,EAC9B,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,EAAE,EACpB,UAAU,CAAC,EAAE,MAAM,EAAE,GACpB,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAoJnD"}