Skip to content
This repository was archived by the owner on Jul 26, 2025. It is now read-only.

Commit 72a3ce9

Browse files
253 new property on roi centroid (#277)
* feat: add centroid property * test: add testing cases for centroid property close: #253 * refactor: redo the algorithm of centroid * refactor: add origin only once the point should be returned * refactor: change names of variables xCoords and yCoords
1 parent 5209949 commit 72a3ce9

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

src/roi/Roi.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ interface Computed {
3333
fillRatio: number;
3434
internalIDs: number[];
3535
feret: Feret;
36+
centroid: Point;
3637
}
3738
export class Roi {
3839
/**
@@ -328,6 +329,29 @@ export class Roi {
328329
};
329330
}
330331

332+
get centroid() {
333+
return this.#getComputed('centroid', () => {
334+
const roiMap = this.getMap();
335+
const data = roiMap.data;
336+
let sumColumn = 0;
337+
let sumRow = 0;
338+
for (let column = 0; column < this.width; column++) {
339+
for (let row = 0; row < this.height; row++) {
340+
let target = this.computeIndex(row, column);
341+
if (data[target] === this.id) {
342+
sumColumn += column;
343+
sumRow += row;
344+
}
345+
}
346+
}
347+
348+
return {
349+
column: sumColumn / this.surface + this.origin.column,
350+
row: sumRow / this.surface + this.origin.row,
351+
};
352+
});
353+
}
354+
331355
#getComputed<T extends keyof Computed>(
332356
property: T,
333357
callback: () => Computed[T],

src/roi/__tests__/centroid.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { fromMask } from '../..';
2+
3+
test('centroid property 4x4', () => {
4+
const mask = testUtils.createMask([
5+
[0, 1, 1, 1],
6+
[0, 1, 0, 1],
7+
[0, 1, 1, 1],
8+
[0, 0, 0, 0],
9+
]);
10+
const roiMapManager = fromMask(mask);
11+
const rois = roiMapManager.getRois();
12+
expect(rois[0].centroid).toStrictEqual({ row: 1, column: 2 });
13+
});
14+
15+
test('border lengths property 5x5', () => {
16+
const mask = testUtils.createMask([
17+
[1, 0, 0, 1, 0],
18+
[1, 1, 1, 1, 0],
19+
[1, 0, 0, 0, 0],
20+
[1, 1, 1, 1, 0],
21+
[1, 1, 1, 0, 0],
22+
]);
23+
const roiMapManager = fromMask(mask);
24+
const rois = roiMapManager.getRois();
25+
expect(rois[0].centroid.row).toBeCloseTo(2.14286);
26+
expect(rois[0].centroid.column).toBeCloseTo(1.28571);
27+
});
28+
29+
test('border lengths property 5x5', () => {
30+
const mask = testUtils.createMask([
31+
[1, 1, 1],
32+
[0, 1, 0],
33+
[1, 1, 1],
34+
]);
35+
const roiMapManager = fromMask(mask);
36+
const rois = roiMapManager.getRois();
37+
expect(rois[0].centroid.row).toBeCloseTo(1);
38+
expect(rois[0].centroid.column).toBeCloseTo(1);
39+
});

0 commit comments

Comments
 (0)