/
manager.js
503 lines (454 loc) · 15.6 KB
/
manager.js
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import Qty from 'js-quantities';
import deepValue from '../../util/deepValue';
import Image from '../Image';
import RoiLayer from './RoiLayer';
import RoiMap from './RoiMap';
import fromMask from './creator/fromMask';
import fromMaskConnectedComponentLabelingAlgorithm from './creator/fromMaskConnectedComponentLabelingAlgorithm';
import fromMaxima from './creator/fromMaxima';
import fromPoints from './creator/fromPoints';
import fromWaterShed from './creator/fromWaterShed';
/**
* A manager of Regions of Interest. A RoiManager is related to a specific Image
* and may contain multiple layers. Each layer is characterized by a label whose is
* name by default 'default'
* @class RoiManager
* @param {Image} image
* @param {object} [options]
*/
export default class RoiManager {
constructor(image, options = {}) {
this._image = image;
this._options = options;
if (!this._options.label) {
this._options.label = 'default';
}
this._layers = {};
this._painted = null;
}
// docs is in the corresponding file
fromMaxima(options = {}) {
let opt = Object.assign({}, this._options, options);
let roiMap = fromMaxima.call(this._image, options);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
}
// docs is in the corresponding file
fromPoints(points, options = {}) {
let opt = Object.assign({}, this._options, options);
let roiMap = fromPoints.call(this._image, points, options);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
return this;
}
/**
* @param {number[]} map
* @param {object} [options]
* @return {this}
*/
putMap(map, options = {}) {
let roiMap = new RoiMap(this._image, map);
let opt = Object.assign({}, this._options, options);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
return this;
}
// docs is in the corresponding file
fromWaterShed(options = {}) {
let opt = Object.assign({}, this._options, options);
let roiMap = fromWaterShed.call(this._image, options);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
}
// docs is in the corresponding file
fromMask(mask, options = {}) {
let opt = Object.assign({}, this._options, options);
let roiMap = fromMask.call(this._image, mask, options);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
return this;
}
fromMaskConnectedComponentLabelingAlgorithm(mask, options = {}) {
let opt = Object.assign({}, this._options, options);
let roiMap = fromMaskConnectedComponentLabelingAlgorithm.call(
this._image,
mask,
options,
);
this._layers[opt.label] = new RoiLayer(roiMap, opt);
return this;
}
/**
*
* @param {object} [options]
* @return {RoiMap}
*/
getMap(options = {}) {
let opt = Object.assign({}, this._options, options);
this._assertLayerWithLabel(opt.label);
return this._layers[opt.label].roiMap;
}
/**
* Return statistics about rows
* @param {object} [options]
* @return {object[]}
*/
rowsInfo(options = {}) {
return this.getMap(options).rowsInfo();
}
/**
* Return statistics about columns
* @param {object} [options]
* @return {object[]}
*/
colsInfo(options = {}) {
return this.getMap(options).rowsInfo();
}
/**
* Return the IDs of the Regions Of Interest (Roi) as an array of number
* @param {object} [options]
* @return {number[]}
*/
getRoiIds(options = {}) {
let rois = this.getRois(options);
if (rois) {
let ids = new Array(rois.length);
for (let i = 0; i < rois.length; i++) {
ids[i] = rois[i].id;
}
return ids;
}
throw new Error('ROIs not found');
}
/**
* Allows to select ROI based on size, label and sign.
* @param {object} [options={}]
* @param {string} [options.label='default'] Label of the layer containing the ROI
* @param {boolean} [options.positive=true] Select the positive region of interest
* @param {boolean} [options.negative=true] Select he negative region of interest
* @param {number} [options.minSurface=0]
* @param {number} [options.maxSurface=Number.POSITIVE_INFINITY]
* @param {number} [options.minWidth=0]
* @param {number} [options.minHeight=Number.POSITIVE_INFINITY]
* @param {number} [options.maxWidth=0]
* @param {number} [options.maxHeight=Number.POSITIVE_INFINITY]
* @param {number} [options.minRatio=0] Ratio width / height
* @param {number} [options.maxRatio=Number.POSITIVE_INFINITY]
* @return {Roi[]}
*/
getRois(options = {}) {
let {
label = this._options.label,
positive = true,
negative = true,
minSurface = 0,
maxSurface = Number.POSITIVE_INFINITY,
minWidth = 0,
maxWidth = Number.POSITIVE_INFINITY,
minHeight = 0,
maxHeight = Number.POSITIVE_INFINITY,
minRatio = 0,
maxRatio = Number.POSITIVE_INFINITY,
} = options;
if (!this._layers[label]) {
throw new Error(`this Roi layer (${label}) does not exist`);
}
const allRois = this._layers[label].roi;
const rois = [];
for (const roi of allRois) {
if (
((roi.id < 0 && negative) || (roi.id > 0 && positive)) &&
roi.surface >= minSurface &&
roi.surface <= maxSurface &&
roi.width >= minWidth &&
roi.width <= maxWidth &&
roi.height >= minHeight &&
roi.height <= maxHeight &&
roi.ratio >= minRatio &&
roi.ratio <= maxRatio
) {
rois.push(roi);
}
}
return rois;
}
/**
* Get an ROI by its id.
* @param {number} roiId
* @param {object} [options={}]
* @param {string} [options.label='default'] Label of the layer containing the ROI
* @return {Roi}
*/
getRoi(roiId, options = {}) {
const { label = this._options.label } = options;
if (!this._layers[label]) {
throw new Error(`this Roi layer (${label}) does not exist`);
}
const roi = this._layers[label].roi.find((roi) => roi.id === roiId);
if (!roi) {
throw new Error(`found no Roi with id ${roiId}`);
}
return roi;
}
/**
* Returns an array of masks
* See {@link Roi.getMask} for the options
* @param {object} [options]
* @return {Image[]} Retuns an array of masks (1 bit Image)
*/
getMasks(options = {}) {
let rois = this.getRois(options);
let masks = new Array(rois.length);
for (let i = 0; i < rois.length; i++) {
masks[i] = rois[i].getMask(options);
}
return masks;
}
/**
* Returns an array of masks
* See {@link Roi.getAnalysisMasks} for the options
* @param {object} [options]
* @return {Image[]} Retuns an array of masks (1 bit Image)
*/
getAnalysisMasks(options = {}) {
const { analysisProperty } = options;
let maskProperty = `${analysisProperty}Mask`;
let rois = this.getRois(options);
if (rois.length === 0 || !rois[0][maskProperty]) return [];
return rois.map((roi) => roi[maskProperty]);
}
/**
*
* @param {object} [options]
* @return {number[]}
*/
getData(options = {}) {
let opt = Object.assign({}, this._options, options);
this._assertLayerWithLabel(opt.label);
return this._layers[opt.label].roiMap.data;
}
/**
* Paint the ROI on a copy of the image and return this image.
* For painting options {@link Image.paintMasks}
* For ROI selection options, see {@link RoiManager.getMasks}
* @param {object} [options] - all the options to select ROIs
* @param {string} [options.labelProperty] - Paint a mask property on the image.
* May be any property of the ROI like
* for example id, surface, width, height, meanX, meanY.
* @param {number} [options.pixelSize] Size of a pixel in SI
* @param {string} [options.unit="pixel"] Unit in which to display the values
* @return {Image} - The painted RGBA 8 bits image
*/
paint(options = {}) {
let { labelProperty, analysisProperty } = options;
if (!this._painted) {
this._painted = this._image.rgba8();
}
let masks = this.getMasks(options);
if (labelProperty) {
const rois = this.getRois(options);
options.labels = rois.map((roi) => deepValue(roi, labelProperty));
const max = Math.max(...options.labels);
let isSurface = false;
let isDistance = false;
if (labelProperty.includes('surface')) {
isSurface = true;
} else if (
/(?:perimeter|min|max|external|width|height|length)/.test(labelProperty)
) {
isDistance = true;
}
if (isFinite(max)) {
let unitLabel = '';
if (
options.unit !== 'pixel' &&
options.pixelSize &&
(isDistance || isSurface)
) {
unitLabel = isSurface ? `${options.unit}^2` : options.unit;
let siLabel = isSurface ? 'm^2' : 'm';
let factor = isSurface ? options.pixelSize ** 2 : options.pixelSize;
const convert = Qty.swiftConverter(siLabel, unitLabel);
options.labels = options.labels.map((value) => {
return convert(factor * value);
});
}
if (max > 50) {
options.labels = options.labels.map(
(number) => Math.round(number) + unitLabel,
);
} else if (max > 10) {
options.labels = options.labels.map(
(number) => number.toFixed(1) + unitLabel,
);
} else {
options.labels = options.labels.map(
(number) => number.toFixed(2) + unitLabel,
);
}
}
options.labelsPosition = rois.map((roi) => [roi.meanX, roi.meanY]);
}
this._painted.paintMasks(masks, options);
if (analysisProperty) {
let analysisMasks = this.getAnalysisMasks(options);
this._painted.paintMasks(analysisMasks, {
color: options.analysisColor,
alpha: options.analysisAlpha,
});
}
return this._painted;
}
// return a mask corresponding to all the selected masks
getMask(options = {}) {
let mask = new Image(this._image.width, this._image.height, {
kind: 'BINARY',
});
let masks = this.getMasks(options);
for (let i = 0; i < masks.length; i++) {
let roi = masks[i];
// we need to find the parent image to calculate the relative position
for (let x = 0; x < roi.width; x++) {
for (let y = 0; y < roi.height; y++) {
if (roi.getBitXY(x, y)) {
mask.setBitXY(x + roi.position[0], y + roi.position[1]);
}
}
}
}
return mask;
}
/**
* Reset the changes to the current painted iamge to the image that was
* used during the creation of the RoiManager except if a new image is
* specified as parameter;
* @param {object} [options]
* @param {Image} [options.image] A new iamge that you would like to sue for painting over
*/
resetPainted(options = {}) {
const { image } = options;
if (image) {
this._painted = this.image.rgba8();
} else {
this._painted = this._image.rgba8();
}
}
/**
* In place modification of the roiMap that joins regions of interest
* @param {object} [options]
* @param {string|function(object,number,number)} [options.algorithm='commonBorderLength'] algorithm used to decide which ROIs are merged.
* Current implemented algorithms are 'commonBorderLength' that use the parameters
* 'minCommonBorderLength' and 'maxCommonBorderLength' as well as 'commonBorderRatio' that uses
* the parameters 'minCommonBorderRatio' and 'maxCommonBorderRatio'.
* @param {number} [options.minCommonBorderLength=5] minimal common number of pixels for merging
* @param {number} [options.maxCommonBorderLength=100] maximal common number of pixels for merging
* @param {number} [options.minCommonBorderRatio=0.3] minimal common border ratio for merging
* @param {number} [options.maxCommonBorderRatio=1] maximal common border ratio for merging
* @return {this}
*/
mergeRoi(options = {}) {
const roiMap = this.getMap(options);
roiMap.mergeRoi(options);
this.putMap(roiMap.data, options);
return this;
}
/**
* Merge multiple rois into one.
* All rois in the provided array will be merged into the first one.
* @param {Array<number>} roiIds - A list of Roi ids to merge
* @param {object} [options]
*/
mergeRois(roiIds, options = {}) {
if (!Array.isArray(roiIds) || roiIds.some((id) => !Number.isInteger(id))) {
throw new Error('Roi ids must be an array of integers');
}
if (roiIds.length < 2) {
throw new Error('Roi ids must have at least two elements');
}
if (new Set(roiIds).size !== roiIds.length) {
throw new Error('Roi ids must be all different');
}
// Throws if one of the ids is wrong
roiIds.forEach((roiId) => this.getRoi(roiId));
const roiMap = this.getMap(options);
roiMap.mergeRois(roiIds);
this.putMap(roiMap.data, options);
return this;
}
/**
* Finds all corresponding ROIs for all ROIs in the manager
* @param {number[]} roiMap
* @param {object} [options]
* @return {Array} array of objects returned in correspondingRoisInformation
*/
findCorrespondingRoi(roiMap, options = {}) {
let allRois = this.getRois(options);
let allRelated = [];
for (let i = 0; i < allRois.length; i++) {
let currentRoi = allRois[i];
let x = currentRoi.minX;
let y = currentRoi.minY;
let allPoints = currentRoi.points;
let roiSign = Math.sign(currentRoi.id);
let currentRelated = correspondingRoisInformation(
x,
y,
allPoints,
roiMap,
roiSign,
);
allRelated.push(currentRelated);
}
return allRelated;
}
_assertLayerWithLabel(label) {
if (!this._layers[label]) {
throw new Error(`no layer with label ${label}`);
}
}
}
/**
* For a given ROI, find corresponding ROIs and properties in given ROIMap.
* Returns an object containing the ID of ROIs, the surface shared by given and corresponding ROIs,
* the percentage of given ROI surface covered by the corresponding ROI, the number of points with same and opposite signs,
* the total number of points (same and opposite).
* @param {number} x - minX value of ROI
* @param {number} y - minY value of ROI
* @param {Array<Array<number>>} points - points of ROI
* @param {Array<number>} roiMap - roiMap from which we get the corresponding ROI
* @param {number} roiSign - sign of ROI
* @return {object} {{id: Array, surface: Array, roiSurfaceCovered: Array, same: number, opposite: number, total: number}}
* @private
*/
function correspondingRoisInformation(x, y, points, roiMap, roiSign) {
let correspondingRois = {
id: [],
surface: [],
roiSurfaceCovered: [],
same: 0,
opposite: 0,
total: 0,
};
for (let i = 0; i < points.length; i++) {
let currentPoint = points[i];
let currentX = currentPoint[0];
let currentY = currentPoint[1];
let correspondingRoiMapIndex = currentX + x + (currentY + y) * roiMap.width;
let value = roiMap.data[correspondingRoiMapIndex];
if (value > 0 || value < 0) {
if (correspondingRois.id.includes(value)) {
correspondingRois.surface[correspondingRois.id.indexOf(value)] += 1;
} else {
correspondingRois.id.push(value);
correspondingRois.surface.push(1);
}
}
}
for (let i = 0; i < correspondingRois.id.length; i++) {
let currentSign = Math.sign(correspondingRois.id[i]);
if (currentSign === roiSign) {
correspondingRois.same += correspondingRois.surface[i];
} else {
correspondingRois.opposite += correspondingRois.surface[i];
}
correspondingRois.roiSurfaceCovered[i] =
correspondingRois.surface[i] / points.length;
}
correspondingRois.total = correspondingRois.opposite + correspondingRois.same;
return correspondingRois;
}