-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathutils.ts
352 lines (327 loc) · 9.42 KB
/
utils.ts
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import {
type GeoTIFF,
type GeoTIFFImage,
fromFile,
fromUrl,
fromBlob
} from 'geotiff';
import { getLabels, DTYPE_LOOKUP } from '../../utils';
import type { OmeXml, PhysicalUnit, DimensionOrder } from '../../omexml';
import type { MultiTiffImage } from '../multi-tiff';
import { createOffsetsProxy } from './proxies';
// TODO: Remove the fancy label stuff
export type OmeTiffDims =
| ['t', 'c', 'z']
| ['z', 't', 'c']
| ['t', 'z', 'c']
| ['c', 'z', 't']
| ['z', 'c', 't']
| ['c', 't', 'z'];
export interface OmeTiffSelection {
t: number;
c: number;
z: number;
}
type PhysicalSize = {
size: number;
unit: PhysicalUnit;
};
type PhysicalSizes = {
x: PhysicalSize;
y: PhysicalSize;
z?: PhysicalSize;
};
function extractPhysicalSizesfromOmeXml(
d: OmeXml[number]['Pixels']
): undefined | PhysicalSizes {
if (
!d['PhysicalSizeX'] ||
!d['PhysicalSizeY'] ||
!d['PhysicalSizeXUnit'] ||
!d['PhysicalSizeYUnit']
) {
return undefined;
}
const physicalSizes: PhysicalSizes = {
x: { size: d['PhysicalSizeX'], unit: d['PhysicalSizeXUnit'] },
y: { size: d['PhysicalSizeY'], unit: d['PhysicalSizeYUnit'] }
};
if (d['PhysicalSizeZ'] && d['PhysicalSizeZUnit']) {
physicalSizes.z = {
size: d['PhysicalSizeZ'],
unit: d['PhysicalSizeZUnit']
};
}
return physicalSizes;
}
export function getOmePixelSourceMeta({ Pixels }: OmeXml[0]) {
// e.g. 'XYZCT' -> ['t', 'c', 'z', 'y', 'x']
const labels = getLabels(Pixels.DimensionOrder);
// Compute "shape" of image
const shape: number[] = Array(labels.length).fill(0);
shape[labels.indexOf('t')] = Pixels.SizeT;
shape[labels.indexOf('c')] = Pixels.SizeC;
shape[labels.indexOf('z')] = Pixels.SizeZ;
// Push extra dimension if data are interleaved.
if (Pixels.Interleaved) {
// @ts-expect-error private, unused dim name for selection
labels.push('_c');
shape.push(3);
}
// Creates a new shape for different level of pyramid.
// Assumes factor-of-two downsampling.
const getShape = (level: number = 0) => {
const s = [...shape];
s[labels.indexOf('x')] = Pixels.SizeX >> level;
s[labels.indexOf('y')] = Pixels.SizeY >> level;
return s;
};
if (!(Pixels.Type in DTYPE_LOOKUP)) {
throw Error(`Pixel type ${Pixels.Type} not supported.`);
}
const dtype = DTYPE_LOOKUP[Pixels.Type as keyof typeof DTYPE_LOOKUP];
const maybePhysicalSizes = extractPhysicalSizesfromOmeXml(Pixels);
if (maybePhysicalSizes) {
return { labels, getShape, dtype, physicalSizes: maybePhysicalSizes };
}
return { labels, getShape, dtype };
}
// Inspired by/borrowed from https://geotiffjs.github.io/geotiff.js/geotiffimage.js.html#line297
function guessImageDataType(image: GeoTIFFImage) {
// Assuming these are flat TIFFs, just grab the info for the first image/sample.
const sampleIndex = 0;
const format = image.fileDirectory.SampleFormat
? image.fileDirectory.SampleFormat[sampleIndex]
: 1;
const bitsPerSample = image.fileDirectory.BitsPerSample[sampleIndex];
switch (format) {
case 1: // unsigned integer data
if (bitsPerSample <= 8) {
return DTYPE_LOOKUP.uint8;
}
if (bitsPerSample <= 16) {
return DTYPE_LOOKUP.uint16;
}
if (bitsPerSample <= 32) {
return DTYPE_LOOKUP.uint32;
}
break;
case 2: // twos complement signed integer data
if (bitsPerSample <= 8) {
return DTYPE_LOOKUP.int8;
}
if (bitsPerSample <= 16) {
return DTYPE_LOOKUP.int16;
}
if (bitsPerSample <= 32) {
return DTYPE_LOOKUP.int32;
}
break;
case 3:
switch (bitsPerSample) {
case 16:
// Should be float 16, maybe 32 will work?
// Or should we raise an error?
return DTYPE_LOOKUP.float;
case 32:
return DTYPE_LOOKUP.float;
case 64:
return DTYPE_LOOKUP.double;
default:
break;
}
break;
default:
break;
}
throw Error('Unsupported data format/bitsPerSample');
}
function getMultiTiffShapeMap(tiffs: MultiTiffImage[]): {
[key: string]: number;
} {
let [c, z, t] = [0, 0, 0];
for (const tiff of tiffs) {
c = Math.max(c, tiff.selection.c);
z = Math.max(z, tiff.selection.z);
t = Math.max(t, tiff.selection.t);
}
const firstTiff = tiffs[0].tiff;
return {
x: firstTiff.getWidth(),
y: firstTiff.getHeight(),
z: z + 1,
c: c + 1,
t: t + 1
};
}
// If a channel has multiple z or t slices with different samples per pixel
// this function will just use the samples per pixel from a random slice.
function getChannelSamplesPerPixel(
tiffs: MultiTiffImage[],
numChannels: number
): number[] {
const channelSamplesPerPixel = Array(numChannels).fill(0);
for (const tiff of tiffs) {
const curChannel = tiff.selection.c;
const curSamplesPerPixel = tiff.tiff.getSamplesPerPixel();
const existingSamplesPerPixel = channelSamplesPerPixel[curChannel];
if (
existingSamplesPerPixel &&
existingSamplesPerPixel != curSamplesPerPixel
) {
throw Error('Channel samples per pixel mismatch');
}
channelSamplesPerPixel[curChannel] = curSamplesPerPixel;
}
return channelSamplesPerPixel;
}
export function getMultiTiffMeta(
dimensionOrder: DimensionOrder,
tiffs: MultiTiffImage[]
) {
const firstTiff = tiffs[0].tiff;
const shapeMap = getMultiTiffShapeMap(tiffs);
const shape = [];
for (const dim of dimensionOrder.toLowerCase()) {
shape.unshift(shapeMap[dim]);
}
const labels = getLabels(dimensionOrder);
const dtype = guessImageDataType(firstTiff);
return { shape, labels, dtype };
}
function getMultiTiffPixelMedatata(
imageNumber: number,
dimensionOrder: DimensionOrder,
shapeMap: { [key: string]: number },
dType: string,
tiffs: MultiTiffImage[],
channelNames: string[],
channelSamplesPerPixel: number[]
) {
const channelMetadata = [];
for (let i = 0; i < shapeMap.c; i += 1) {
channelMetadata.push({
ID: `Channel:${imageNumber}:${i}`,
Name: channelNames[i],
SamplesPerPixel: channelSamplesPerPixel[i]
});
}
return {
BigEndian: !tiffs[0].tiff.littleEndian,
DimensionOrder: dimensionOrder,
ID: `Pixels:${imageNumber}`,
SizeC: shapeMap.c,
SizeT: shapeMap.t,
SizeX: shapeMap.x,
SizeY: shapeMap.y,
SizeZ: shapeMap.z,
Type: dType,
Channels: channelMetadata
};
}
export function getMultiTiffMetadata(
imageName: string,
tiffImages: MultiTiffImage[],
channelNames: string[],
dimensionOrder: DimensionOrder,
dType: string
) {
const imageNumber = 0;
const id = `Image:${imageNumber}`;
const date = '';
const description = '';
const shapeMap = getMultiTiffShapeMap(tiffImages);
const channelSamplesPerPixel = getChannelSamplesPerPixel(
tiffImages,
shapeMap.c
);
if (channelNames.length !== shapeMap.c)
throw Error(
'Wrong number of channel names for number of channels provided'
);
const pixels = getMultiTiffPixelMedatata(
imageNumber,
dimensionOrder,
shapeMap,
dType,
tiffImages,
channelNames,
channelSamplesPerPixel
);
const format = () => {
return {
'Acquisition Date': date,
'Dimensions (XY)': `${shapeMap.x} x ${shapeMap.y}`,
PixelsType: dType,
'Z-sections/Timepoints': `${shapeMap.z} x ${shapeMap.t}`,
Channels: shapeMap.c
};
};
return {
ID: id,
Name: imageName,
AcquisitionDate: date,
Description: description,
Pixels: pixels,
format
};
}
export function parseFilename(path: string) {
const parsedFilename: { name?: string; extension?: string } = {};
const filename = path.split('/').pop();
const splitFilename = filename?.split('.');
if (splitFilename) {
parsedFilename.name = splitFilename.slice(0, -1).join('.');
[, parsedFilename.extension] = splitFilename;
}
return parsedFilename;
}
/**
* Creates a GeoTIFF object from a URL, File, or Blob.
*
* @param source - URL, File, or Blob
* @param options
* @param options.headers - HTTP headers to use when fetching a URL
*/
function createGeoTiffObject(
source: string | URL | File,
{ headers }: { headers?: Headers | Record<string, string> }
): Promise<GeoTIFF> {
if (source instanceof Blob) {
return fromBlob(source);
}
const url = typeof source === 'string' ? new URL(source) : source;
if (url.protocol === 'file:') {
return fromFile(url.pathname);
}
// https://github.com/ilan-gold/geotiff.js/tree/viv#abortcontroller-support
// https://www.npmjs.com/package/lru-cache#options
// Cache size needs to be infinite due to consistency issues.
return fromUrl(url.href, { headers, cacheSize: Infinity });
}
/**
* Creates a GeoTIFF object from a URL, File, or Blob.
*
* If `offsets` are provided, a proxy is returned that
* intercepts calls to `tiff.getImage` and injects the
* pre-computed offsets. This is a performance enhancement.
*
* @param source - URL, File, or Blob
* @param options
* @param options.headers - HTTP headers to use when fetching a URL
*/
export async function createGeoTiff(
source: string | URL | File,
options: {
headers?: Headers | Record<string, string>;
offsets?: number[];
} = {}
): Promise<GeoTIFF> {
const tiff = await createGeoTiffObject(source, options);
/*
* Performance enhancement. If offsets are provided, we
* create a proxy that intercepts calls to `tiff.getImage`
* and injects the pre-computed offsets.
*/
return options.offsets ? createOffsetsProxy(tiff, options.offsets) : tiff;
}