@rosepetal/node-red-contrib-image-tools 1.3.2 → 1.4.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.
- package/node-red-contrib-image-tools/lib/cpp-bridge.js +4 -4
- package/node-red-contrib-image-tools/lib/inference-transform.js +688 -0
- package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +10 -10
- package/node-red-contrib-image-tools/nodes/io/image-out.js +0 -1
- package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +72 -1
- package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +25 -0
- package/node-red-contrib-image-tools/nodes/mix/concat.html +74 -3
- package/node-red-contrib-image-tools/nodes/mix/concat.js +23 -0
- package/node-red-contrib-image-tools/nodes/mix/mosaic.html +72 -1
- package/node-red-contrib-image-tools/nodes/mix/mosaic.js +25 -0
- package/node-red-contrib-image-tools/nodes/transform/crop.html +76 -5
- package/node-red-contrib-image-tools/nodes/transform/crop.js +31 -0
- package/node-red-contrib-image-tools/nodes/transform/padding.html +76 -5
- package/node-red-contrib-image-tools/nodes/transform/padding.js +24 -0
- package/node-red-contrib-image-tools/nodes/transform/resize.html +76 -3
- package/node-red-contrib-image-tools/nodes/transform/resize.js +30 -0
- package/node-red-contrib-image-tools/nodes/transform/rotate.html +77 -4
- package/node-red-contrib-image-tools/nodes/transform/rotate.js +25 -0
- package/package.json +2 -35
- package/rosepetal-image-engine/src/add-bbs.cpp +48 -21
- package/scripts/dual-register.js +0 -30
|
@@ -173,14 +173,14 @@ function tryBuildFromSource() {
|
|
|
173
173
|
function loadAddon() {
|
|
174
174
|
const platformId = detectPlatform();
|
|
175
175
|
|
|
176
|
-
// 1. Try
|
|
177
|
-
let addon =
|
|
176
|
+
// 1. Try local build first (development / install.sh)
|
|
177
|
+
let addon = tryLoadFromLocalBuild();
|
|
178
178
|
if (addon) {
|
|
179
179
|
return addon;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
// 2. Try
|
|
183
|
-
addon =
|
|
182
|
+
// 2. Try platform-specific package (npm install without build tools)
|
|
183
|
+
addon = tryLoadFromPackage(platformId);
|
|
184
184
|
if (addon) {
|
|
185
185
|
return addon;
|
|
186
186
|
}
|
|
@@ -0,0 +1,688 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inference coordinate transform library.
|
|
3
|
+
* Transforms detection/segmentation coordinates when images are geometrically modified.
|
|
4
|
+
* Pure JavaScript — no dependency on Node-RED runtime.
|
|
5
|
+
*/
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
9
|
+
|
|
10
|
+
function clipNorm(v) { return Math.max(0, Math.min(1, v)); }
|
|
11
|
+
|
|
12
|
+
function deepClone(obj) {
|
|
13
|
+
if (obj === null || typeof obj !== 'object') return obj;
|
|
14
|
+
if (Buffer.isBuffer(obj)) return Buffer.from(obj);
|
|
15
|
+
if (Array.isArray(obj)) return obj.map(deepClone);
|
|
16
|
+
const out = {};
|
|
17
|
+
for (const k of Object.keys(obj)) out[k] = deepClone(obj[k]);
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function transformPoints(points, fn) {
|
|
22
|
+
return points.map(p => fn(p[0], p[1]));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function clipPoints(points) {
|
|
26
|
+
return points.map(p => [clipNorm(p[0]), clipNorm(p[1])]);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Shoelace formula — returns absolute area of a polygon in normalized coords. */
|
|
30
|
+
function shoelaceArea(polygon) {
|
|
31
|
+
let a = 0;
|
|
32
|
+
const n = polygon.length;
|
|
33
|
+
for (let i = 0; i < n; i++) {
|
|
34
|
+
const j = (i + 1) % n;
|
|
35
|
+
a += polygon[i][0] * polygon[j][1];
|
|
36
|
+
a -= polygon[j][0] * polygon[i][1];
|
|
37
|
+
}
|
|
38
|
+
return Math.abs(a) / 2;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ─── Box Format Conversion ──────────────────────────────────────────────────
|
|
42
|
+
|
|
43
|
+
/** xywhr (top-left origin, rotation in degrees) → 4 corners [TL, TR, BR, BL] */
|
|
44
|
+
function xywhrToCorners(x, y, w, h, r) {
|
|
45
|
+
const rad = r * Math.PI / 180;
|
|
46
|
+
const cos = Math.cos(rad), sin = Math.sin(rad);
|
|
47
|
+
return [
|
|
48
|
+
[x, y],
|
|
49
|
+
[x + w * cos, y + w * sin],
|
|
50
|
+
[x + w * cos - h * sin, y + w * sin + h * cos],
|
|
51
|
+
[x - h * sin, y + h * cos]
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** cwh (center origin, rotation in degrees) → 4 corners [TL, TR, BR, BL] */
|
|
56
|
+
function cwhToCorners(cx, cy, w, h, r) {
|
|
57
|
+
const rad = r * Math.PI / 180;
|
|
58
|
+
const cos = Math.cos(rad), sin = Math.sin(rad);
|
|
59
|
+
const hw = w / 2, hh = h / 2;
|
|
60
|
+
return [
|
|
61
|
+
[cx - hw * cos + hh * sin, cy - hw * sin - hh * cos],
|
|
62
|
+
[cx + hw * cos + hh * sin, cy + hw * sin - hh * cos],
|
|
63
|
+
[cx + hw * cos - hh * sin, cy + hw * sin + hh * cos],
|
|
64
|
+
[cx - hw * cos - hh * sin, cy - hw * sin + hh * cos]
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Ensure a detection object has `raw_boxes` by converting from whichever
|
|
70
|
+
* format is available. Priority: raw_boxes > 4points > xywhr > cwh > 2points.
|
|
71
|
+
*/
|
|
72
|
+
function ensureRawBoxes(det) {
|
|
73
|
+
if (det.raw_boxes && Array.isArray(det.raw_boxes) && det.raw_boxes.length === 4) return;
|
|
74
|
+
|
|
75
|
+
if (det['4points']) {
|
|
76
|
+
const p = det['4points'];
|
|
77
|
+
det.raw_boxes = [[p.x0, p.y0], [p.x1, p.y1], [p.x2, p.y2], [p.x3, p.y3]];
|
|
78
|
+
} else if (det.xywhr) {
|
|
79
|
+
const { x, y, w, h, r } = det.xywhr;
|
|
80
|
+
det.raw_boxes = xywhrToCorners(x, y, w, h, r);
|
|
81
|
+
} else if (det.cwh) {
|
|
82
|
+
const { x, y, w, h, r } = det.cwh;
|
|
83
|
+
det.raw_boxes = cwhToCorners(x, y, w, h, r);
|
|
84
|
+
} else if (det['2points']) {
|
|
85
|
+
const { xmin, ymin, xmax, ymax } = det['2points'];
|
|
86
|
+
det.raw_boxes = [[xmin, ymin], [xmax, ymin], [xmax, ymax], [xmin, ymax]];
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Re-sort 4 corner points into canonical clockwise order: TL, TR, BR, BL.
|
|
92
|
+
* After geometric transforms (rotation, etc.) the point order may change.
|
|
93
|
+
*/
|
|
94
|
+
function reorderBoxPoints(points) {
|
|
95
|
+
if (!points || points.length !== 4) return points;
|
|
96
|
+
|
|
97
|
+
// Sort by y ascending (top points first), break ties by x
|
|
98
|
+
const sorted = [...points].sort((a, b) => a[1] - b[1] || a[0] - b[0]);
|
|
99
|
+
|
|
100
|
+
// Top two points: smaller x = TL, larger x = TR
|
|
101
|
+
const top = sorted.slice(0, 2).sort((a, b) => a[0] - b[0]);
|
|
102
|
+
// Bottom two points: larger x = BR, smaller x = BL
|
|
103
|
+
const bot = sorted.slice(2, 4).sort((a, b) => b[0] - a[0]);
|
|
104
|
+
|
|
105
|
+
return [top[0], top[1], bot[0], bot[1]]; // TL, TR, BR, BL
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ─── Box Format Recalculation ───────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Given a detection with transformed `raw_boxes`, recalculate all derived
|
|
112
|
+
* box formats that were present on the original detection.
|
|
113
|
+
*/
|
|
114
|
+
function recalculateBoxFormats(det) {
|
|
115
|
+
// Do NOT reorder points — edge topology must be preserved for oriented boxes.
|
|
116
|
+
// Point 0→1 is always the width edge, point 0→3 is the height edge.
|
|
117
|
+
const rb = det.raw_boxes; // [[x0,y0],[x1,y1],[x2,y2],[x3,y3]]
|
|
118
|
+
|
|
119
|
+
// 2points — only valid for axis-aligned boxes; remove if box is oriented
|
|
120
|
+
if (det.hasOwnProperty('2points')) {
|
|
121
|
+
const dx = rb[1][0] - rb[0][0];
|
|
122
|
+
const dy = rb[1][1] - rb[0][1];
|
|
123
|
+
const isAxisAligned = Math.abs(dy) < 1e-6 && Math.abs(rb[0][1] - rb[1][1]) < 1e-6;
|
|
124
|
+
if (isAxisAligned) {
|
|
125
|
+
const xs = rb.map(p => p[0]), ys = rb.map(p => p[1]);
|
|
126
|
+
det['2points'] = {
|
|
127
|
+
xmin: Math.min(...xs), ymin: Math.min(...ys),
|
|
128
|
+
xmax: Math.max(...xs), ymax: Math.max(...ys)
|
|
129
|
+
};
|
|
130
|
+
} else {
|
|
131
|
+
delete det['2points'];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 4points — flat
|
|
136
|
+
if (det.hasOwnProperty('4points')) {
|
|
137
|
+
det['4points'] = {
|
|
138
|
+
x0: rb[0][0], y0: rb[0][1],
|
|
139
|
+
x1: rb[1][0], y1: rb[1][1],
|
|
140
|
+
x2: rb[2][0], y2: rb[2][1],
|
|
141
|
+
x3: rb[3][0], y3: rb[3][1]
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Oriented box metrics (shared by xywhr and cwh)
|
|
146
|
+
const dx = rb[1][0] - rb[0][0];
|
|
147
|
+
const dy = rb[1][1] - rb[0][1];
|
|
148
|
+
const w = Math.sqrt(dx * dx + dy * dy);
|
|
149
|
+
const dx2 = rb[3][0] - rb[0][0];
|
|
150
|
+
const dy2 = rb[3][1] - rb[0][1];
|
|
151
|
+
const h = Math.sqrt(dx2 * dx2 + dy2 * dy2);
|
|
152
|
+
const r = Math.atan2(dy, dx) * (180 / Math.PI);
|
|
153
|
+
|
|
154
|
+
// xywhr — top-left, width, height, rotation
|
|
155
|
+
if (det.hasOwnProperty('xywhr')) {
|
|
156
|
+
det.xywhr = { x: rb[0][0], y: rb[0][1], w, h, r };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// cwh — center, width, height, rotation
|
|
160
|
+
if (det.hasOwnProperty('cwh')) {
|
|
161
|
+
const cx = (rb[0][0] + rb[2][0]) / 2;
|
|
162
|
+
const cy = (rb[0][1] + rb[2][1]) / 2;
|
|
163
|
+
det.cwh = { x: cx, y: cy, w, h, r };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ─── Overlap computation ────────────────────────────────────────────────────
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Compute the fraction of a detection's axis-aligned bounding box that
|
|
171
|
+
* overlaps with the crop window (all in normalized coords).
|
|
172
|
+
*/
|
|
173
|
+
function overlapFraction(rawBoxes, cropRegion) {
|
|
174
|
+
const { x0, y0, w, h } = cropRegion;
|
|
175
|
+
const xs = rawBoxes.map(p => p[0]), ys = rawBoxes.map(p => p[1]);
|
|
176
|
+
const bxMin = Math.min(...xs), bxMax = Math.max(...xs);
|
|
177
|
+
const byMin = Math.min(...ys), byMax = Math.max(...ys);
|
|
178
|
+
|
|
179
|
+
const bArea = (bxMax - bxMin) * (byMax - byMin);
|
|
180
|
+
if (bArea <= 0) return 0;
|
|
181
|
+
|
|
182
|
+
const ixMin = Math.max(bxMin, x0);
|
|
183
|
+
const iyMin = Math.max(byMin, y0);
|
|
184
|
+
const ixMax = Math.min(bxMax, x0 + w);
|
|
185
|
+
const iyMax = Math.min(byMax, y0 + h);
|
|
186
|
+
|
|
187
|
+
const iw = Math.max(0, ixMax - ixMin);
|
|
188
|
+
const ih = Math.max(0, iyMax - iyMin);
|
|
189
|
+
return (iw * ih) / bArea;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ─── Detection Transform ────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* @param {object} det — detection with raw_boxes
|
|
196
|
+
* @param {function} pointFn — (x,y) => [nx,ny]
|
|
197
|
+
* @param {object} opts — { clip, cropRegion, minOverlap }
|
|
198
|
+
* @returns {object|null} transformed detection or null if filtered out
|
|
199
|
+
*/
|
|
200
|
+
function transformDetection(det, pointFn, opts = {}) {
|
|
201
|
+
// Convert any input format to raw_boxes if not already present
|
|
202
|
+
ensureRawBoxes(det);
|
|
203
|
+
|
|
204
|
+
// Check overlap before cloning (optimization)
|
|
205
|
+
if (opts.cropRegion) {
|
|
206
|
+
const frac = overlapFraction(det.raw_boxes, opts.cropRegion);
|
|
207
|
+
if (frac < (opts.minOverlap || 0.1)) return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const d = deepClone(det);
|
|
211
|
+
d.raw_boxes = transformPoints(d.raw_boxes, pointFn);
|
|
212
|
+
if (opts.clip) d.raw_boxes = clipPoints(d.raw_boxes);
|
|
213
|
+
recalculateBoxFormats(d);
|
|
214
|
+
return d;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ─── Segmentation Transform ─────────────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @param {object} seg — segmentation with polygons and optional mask
|
|
221
|
+
* @param {function} pointFn
|
|
222
|
+
* @param {object} opts — { clip, maskTransformFn }
|
|
223
|
+
* @returns {Promise<object|null>}
|
|
224
|
+
*/
|
|
225
|
+
async function transformSegmentation(seg, pointFn, opts = {}) {
|
|
226
|
+
const s = deepClone(seg);
|
|
227
|
+
|
|
228
|
+
// Transform polygons
|
|
229
|
+
if (s.polygons && Array.isArray(s.polygons)) {
|
|
230
|
+
s.polygons = s.polygons.map(contour => {
|
|
231
|
+
let pts = transformPoints(contour, pointFn);
|
|
232
|
+
if (opts.clip) pts = clipPoints(pts);
|
|
233
|
+
return pts;
|
|
234
|
+
}).filter(c => c.length >= 3);
|
|
235
|
+
|
|
236
|
+
// Recalculate area
|
|
237
|
+
s.area = s.polygons.reduce((sum, c) => sum + shoelaceArea(c), 0);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Segmentations from the inferencer may also carry raw_boxes — transform them too
|
|
241
|
+
if (s.raw_boxes && Array.isArray(s.raw_boxes) && s.raw_boxes.length === 4) {
|
|
242
|
+
s.raw_boxes = transformPoints(s.raw_boxes, pointFn);
|
|
243
|
+
if (opts.clip) s.raw_boxes = clipPoints(s.raw_boxes);
|
|
244
|
+
s.raw_boxes = reorderBoxPoints(s.raw_boxes);
|
|
245
|
+
recalculateBoxFormats(s);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Transform bitmap mask
|
|
249
|
+
if (s.mask && opts.maskTransformFn) {
|
|
250
|
+
try {
|
|
251
|
+
s.mask = await opts.maskTransformFn(s.mask);
|
|
252
|
+
} catch (e) {
|
|
253
|
+
// Non-fatal: drop the mask if transform fails
|
|
254
|
+
delete s.mask;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Filter out if nothing useful remains
|
|
259
|
+
if ((!s.polygons || s.polygons.length === 0) && !s.mask) return null;
|
|
260
|
+
|
|
261
|
+
return s;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ─── Per-Transform Point Function Makers ────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
function makeResizeTransform(params) {
|
|
267
|
+
// Normalized coords are invariant under resize — identity for points.
|
|
268
|
+
// Bitmap masks DO need resizing though.
|
|
269
|
+
const { origW, origH, newW, newH } = params;
|
|
270
|
+
return {
|
|
271
|
+
pointFn: (x, y) => [x, y],
|
|
272
|
+
opts: {},
|
|
273
|
+
maskTransformFn: (newW && newH && (newW !== origW || newH !== origH))
|
|
274
|
+
? async (mask, cppBridge) => {
|
|
275
|
+
const { image } = await cppBridge.resize(mask, 'set', newW, 'set', newH, 'raw', 90, false);
|
|
276
|
+
return image;
|
|
277
|
+
}
|
|
278
|
+
: null,
|
|
279
|
+
_maskParams: { type: 'resize', newW, newH }
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function makeRotateTransform(params) {
|
|
284
|
+
const { angleDeg, origW, origH } = params;
|
|
285
|
+
const DEG = Math.PI / 180;
|
|
286
|
+
const eps = 1e-3;
|
|
287
|
+
const norm = ((angleDeg % 360) + 360) % 360;
|
|
288
|
+
|
|
289
|
+
// Fast paths for exact 90/180/270
|
|
290
|
+
const near = (a) => Math.abs(norm - a) < eps;
|
|
291
|
+
|
|
292
|
+
if (near(0)) {
|
|
293
|
+
return { pointFn: (x, y) => [x, y], opts: {}, maskTransformFn: null };
|
|
294
|
+
}
|
|
295
|
+
if (near(90)) {
|
|
296
|
+
// C++ uses cv::ROTATE_90_COUNTERCLOCKWISE for angle=90
|
|
297
|
+
return {
|
|
298
|
+
pointFn: (x, y) => [y, 1 - x],
|
|
299
|
+
opts: {},
|
|
300
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
301
|
+
const { image } = await cppBridge.rotate(mask, 90, '#00000000', 'raw', 90, false);
|
|
302
|
+
return image;
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
if (near(180)) {
|
|
307
|
+
return {
|
|
308
|
+
pointFn: (x, y) => [1 - x, 1 - y],
|
|
309
|
+
opts: {},
|
|
310
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
311
|
+
const { image } = await cppBridge.rotate(mask, 180, '#00000000', 'raw', 90, false);
|
|
312
|
+
return image;
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
if (near(270)) {
|
|
317
|
+
// C++ uses cv::ROTATE_90_CLOCKWISE for angle=270
|
|
318
|
+
return {
|
|
319
|
+
pointFn: (x, y) => [1 - y, x],
|
|
320
|
+
opts: {},
|
|
321
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
322
|
+
const { image } = await cppBridge.rotate(mask, 270, '#00000000', 'raw', 90, false);
|
|
323
|
+
return image;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Arbitrary angle — replicate OpenCV getRotationMatrix2D + adjust
|
|
329
|
+
const rad = angleDeg * DEG;
|
|
330
|
+
const cosA = Math.cos(rad), sinA = Math.sin(rad);
|
|
331
|
+
const absCos = Math.abs(cosA), absSin = Math.abs(sinA);
|
|
332
|
+
const W = origW, H = origH;
|
|
333
|
+
const newW = Math.round(H * absSin + W * absCos);
|
|
334
|
+
const newH = Math.round(H * absCos + W * absSin);
|
|
335
|
+
const cx = W / 2, cy = H / 2;
|
|
336
|
+
|
|
337
|
+
// Affine matrix coefficients (matching rotate.cpp:73-80)
|
|
338
|
+
const alpha = cosA, beta = sinA;
|
|
339
|
+
const m02 = (1 - alpha) * cx - beta * cy + (newW / 2 - cx);
|
|
340
|
+
const m12 = beta * cx + (1 - alpha) * cy + (newH / 2 - cy);
|
|
341
|
+
|
|
342
|
+
return {
|
|
343
|
+
pointFn: (nx, ny) => {
|
|
344
|
+
const px = nx * W;
|
|
345
|
+
const py = ny * H;
|
|
346
|
+
const px2 = alpha * px + beta * py + m02;
|
|
347
|
+
const py2 = -beta * px + alpha * py + m12;
|
|
348
|
+
return [px2 / newW, py2 / newH];
|
|
349
|
+
},
|
|
350
|
+
opts: {},
|
|
351
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
352
|
+
const { image } = await cppBridge.rotate(mask, angleDeg, '#00000000', 'raw', 90, false);
|
|
353
|
+
return image;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function makeCropTransform(params) {
|
|
359
|
+
const { x0, y0, w, h } = params; // all normalized 0-1
|
|
360
|
+
return {
|
|
361
|
+
pointFn: (nx, ny) => [(nx - x0) / w, (ny - y0) / h],
|
|
362
|
+
opts: { clip: true, cropRegion: { x0, y0, w, h }, minOverlap: 0.1 },
|
|
363
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
364
|
+
const { image } = await cppBridge.crop(mask, x0, y0, w, h, true, 'raw', 90, false);
|
|
365
|
+
return image;
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function makePaddingTransform(params) {
|
|
371
|
+
const { top, bottom, left, right, origW, origH } = params;
|
|
372
|
+
const newW = origW + left + right;
|
|
373
|
+
const newH = origH + top + bottom;
|
|
374
|
+
return {
|
|
375
|
+
pointFn: (nx, ny) => [
|
|
376
|
+
(nx * origW + left) / newW,
|
|
377
|
+
(ny * origH + top) / newH
|
|
378
|
+
],
|
|
379
|
+
opts: {},
|
|
380
|
+
maskTransformFn: async (mask, cppBridge) => {
|
|
381
|
+
const { image } = await cppBridge.padding(mask, top, bottom, left, right, '#00000000', 'raw', 90, false);
|
|
382
|
+
return image;
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// ─── Multi-Image Transform Makers ───────────────────────────────────────────
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Concat: returns an array of transform infos, one per input image.
|
|
391
|
+
* Must replicate the sizing logic from concat.cpp.
|
|
392
|
+
*/
|
|
393
|
+
function makeConcatTransforms(params) {
|
|
394
|
+
const { direction, strategy, imageDims } = params;
|
|
395
|
+
const isHorizontal = direction === 'right' || direction === 'left';
|
|
396
|
+
|
|
397
|
+
// Max cross-axis dimension
|
|
398
|
+
const maxCross = isHorizontal
|
|
399
|
+
? Math.max(...imageDims.map(d => d.height))
|
|
400
|
+
: Math.max(...imageDims.map(d => d.width));
|
|
401
|
+
|
|
402
|
+
// Compute placed dimensions and offsets for each image
|
|
403
|
+
const placements = [];
|
|
404
|
+
for (const dim of imageDims) {
|
|
405
|
+
let placedW, placedH, padBefore = 0;
|
|
406
|
+
|
|
407
|
+
if (strategy === 'resize') {
|
|
408
|
+
if (isHorizontal) {
|
|
409
|
+
const scale = maxCross / dim.height;
|
|
410
|
+
placedW = Math.round(dim.width * scale);
|
|
411
|
+
placedH = maxCross;
|
|
412
|
+
} else {
|
|
413
|
+
const scale = maxCross / dim.width;
|
|
414
|
+
placedW = maxCross;
|
|
415
|
+
placedH = Math.round(dim.height * scale);
|
|
416
|
+
}
|
|
417
|
+
} else {
|
|
418
|
+
placedW = dim.width;
|
|
419
|
+
placedH = dim.height;
|
|
420
|
+
const delta = isHorizontal ? (maxCross - dim.height) : (maxCross - dim.width);
|
|
421
|
+
if (delta > 0) {
|
|
422
|
+
if (strategy === 'pad-start') padBefore = delta;
|
|
423
|
+
else if (strategy === 'pad-end') padBefore = 0;
|
|
424
|
+
else padBefore = Math.floor(delta / 2); // pad-both
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
placements.push({ placedW, placedH, padBefore, origW: dim.width, origH: dim.height });
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Compute offsets along main axis
|
|
431
|
+
let offset = 0;
|
|
432
|
+
// For direction=up, C++ reverses tile order before vconcat
|
|
433
|
+
const order = (direction === 'up') ? [...placements].reverse() : placements;
|
|
434
|
+
|
|
435
|
+
// Build offset array indexed by original image index
|
|
436
|
+
const offsetByIdx = new Array(placements.length);
|
|
437
|
+
for (let oi = 0; oi < order.length; oi++) {
|
|
438
|
+
const origIdx = (direction === 'up') ? (placements.length - 1 - oi) : oi;
|
|
439
|
+
if (isHorizontal) {
|
|
440
|
+
offsetByIdx[origIdx] = { x: offset, y: 0 };
|
|
441
|
+
offset += order[oi].placedW;
|
|
442
|
+
} else {
|
|
443
|
+
offsetByIdx[origIdx] = { x: 0, y: offset };
|
|
444
|
+
offset += order[oi].placedH;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// Total result dimensions
|
|
449
|
+
let totalW, totalH;
|
|
450
|
+
if (isHorizontal) {
|
|
451
|
+
totalW = placements.reduce((s, p) => s + p.placedW, 0);
|
|
452
|
+
totalH = maxCross;
|
|
453
|
+
} else {
|
|
454
|
+
totalW = maxCross;
|
|
455
|
+
totalH = placements.reduce((s, p) => s + p.placedH, 0);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Build transforms per image
|
|
459
|
+
const transforms = placements.map((pl, i) => {
|
|
460
|
+
const off = offsetByIdx[i];
|
|
461
|
+
const rW = totalW, rH = totalH;
|
|
462
|
+
|
|
463
|
+
let pointFn;
|
|
464
|
+
if (strategy === 'resize') {
|
|
465
|
+
pointFn = (nx, ny) => {
|
|
466
|
+
const px = nx * pl.placedW + off.x;
|
|
467
|
+
const py = ny * pl.placedH + off.y;
|
|
468
|
+
return [px / rW, py / rH];
|
|
469
|
+
};
|
|
470
|
+
} else {
|
|
471
|
+
// Padding strategy: coords map to original-sized area within padded tile
|
|
472
|
+
const padOffX = isHorizontal ? 0 : pl.padBefore;
|
|
473
|
+
const padOffY = isHorizontal ? pl.padBefore : 0;
|
|
474
|
+
pointFn = (nx, ny) => {
|
|
475
|
+
const px = nx * pl.origW + off.x + padOffX;
|
|
476
|
+
const py = ny * pl.origH + off.y + padOffY;
|
|
477
|
+
return [px / rW, py / rH];
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
return { pointFn, opts: {} };
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
// For direction=left, C++ flips the entire result horizontally
|
|
485
|
+
if (direction === 'left') {
|
|
486
|
+
for (const t of transforms) {
|
|
487
|
+
const origFn = t.pointFn;
|
|
488
|
+
t.pointFn = (nx, ny) => {
|
|
489
|
+
const [x2, y2] = origFn(nx, ny);
|
|
490
|
+
return [1 - x2, y2];
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
return transforms;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* Mosaic: returns Map<arrayIndex, transformInfo[]>.
|
|
500
|
+
* Each image can appear at multiple positions on the canvas.
|
|
501
|
+
*/
|
|
502
|
+
function makeMosaicTransform(params) {
|
|
503
|
+
const { positions, canvasW, canvasH, imageDims, normalized } = params;
|
|
504
|
+
const byImage = new Map();
|
|
505
|
+
|
|
506
|
+
for (const pos of positions) {
|
|
507
|
+
const idx = parseInt(pos.arrayIndex);
|
|
508
|
+
if (idx < 0 || idx >= imageDims.length) continue;
|
|
509
|
+
const imgW = imageDims[idx].width;
|
|
510
|
+
const imgH = imageDims[idx].height;
|
|
511
|
+
|
|
512
|
+
const posXpx = normalized ? pos.x * canvasW : pos.x;
|
|
513
|
+
const posYpx = normalized ? pos.y * canvasH : pos.y;
|
|
514
|
+
|
|
515
|
+
const tx = {
|
|
516
|
+
pointFn: (nx, ny) => [
|
|
517
|
+
(nx * imgW + posXpx) / canvasW,
|
|
518
|
+
(ny * imgH + posYpx) / canvasH
|
|
519
|
+
],
|
|
520
|
+
opts: { clip: true }
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
if (!byImage.has(idx)) byImage.set(idx, []);
|
|
524
|
+
byImage.get(idx).push(tx);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return byImage;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* Advanced mosaic: like mosaic but with per-image resize and rotation.
|
|
532
|
+
*/
|
|
533
|
+
function makeAdvancedMosaicTransform(params) {
|
|
534
|
+
const { imageConfigs, canvasW, canvasH, imageDims, normalized } = params;
|
|
535
|
+
const byImage = new Map();
|
|
536
|
+
|
|
537
|
+
for (const cfg of imageConfigs) {
|
|
538
|
+
const idx = parseInt(cfg.arrayIndex);
|
|
539
|
+
if (idx < 0 || idx >= imageDims.length) continue;
|
|
540
|
+
|
|
541
|
+
const origW = imageDims[idx].width;
|
|
542
|
+
const origH = imageDims[idx].height;
|
|
543
|
+
|
|
544
|
+
// Placed dimensions (after optional resize)
|
|
545
|
+
const placedW = (cfg.width && cfg.width > 0) ? cfg.width : origW;
|
|
546
|
+
const placedH = (cfg.height && cfg.height > 0) ? cfg.height : origH;
|
|
547
|
+
|
|
548
|
+
const posXpx = normalized ? cfg.x * canvasW : cfg.x;
|
|
549
|
+
const posYpx = normalized ? cfg.y * canvasH : cfg.y;
|
|
550
|
+
const rotation = cfg.rotation || 0;
|
|
551
|
+
|
|
552
|
+
let pointFn;
|
|
553
|
+
if (Math.abs(rotation) < 1e-3) {
|
|
554
|
+
// No rotation — just scale + place
|
|
555
|
+
pointFn = (nx, ny) => [
|
|
556
|
+
(nx * placedW + posXpx) / canvasW,
|
|
557
|
+
(ny * placedH + posYpx) / canvasH
|
|
558
|
+
];
|
|
559
|
+
} else {
|
|
560
|
+
// Rotation around placed image center, then place on canvas
|
|
561
|
+
const rad = rotation * Math.PI / 180;
|
|
562
|
+
const cosA = Math.cos(rad), sinA = Math.sin(rad);
|
|
563
|
+
const pcx = placedW / 2, pcy = placedH / 2;
|
|
564
|
+
|
|
565
|
+
pointFn = (nx, ny) => {
|
|
566
|
+
// Scale to placed pixel coords
|
|
567
|
+
const px = nx * placedW - pcx;
|
|
568
|
+
const py = ny * placedH - pcy;
|
|
569
|
+
// Rotate
|
|
570
|
+
const rx = px * cosA - py * sinA + pcx;
|
|
571
|
+
const ry = px * sinA + py * cosA + pcy;
|
|
572
|
+
// Place on canvas
|
|
573
|
+
return [(rx + posXpx) / canvasW, (ry + posYpx) / canvasH];
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
const tx = { pointFn, opts: { clip: true } };
|
|
578
|
+
if (!byImage.has(idx)) byImage.set(idx, []);
|
|
579
|
+
byImage.get(idx).push(tx);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
return byImage;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// ─── High-Level Orchestrators ───────────────────────────────────────────────
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Apply a single transform to an array of inferences (detections + segmentations mixed).
|
|
589
|
+
* @param {Array} inferences
|
|
590
|
+
* @param {object} txInfo — { pointFn, opts, maskTransformFn }
|
|
591
|
+
* @param {object} cppBridge — for bitmap mask transforms
|
|
592
|
+
* @returns {Promise<Array>}
|
|
593
|
+
*/
|
|
594
|
+
async function applyTransform(inferences, txInfo, cppBridge) {
|
|
595
|
+
if (!inferences || !Array.isArray(inferences) || inferences.length === 0) {
|
|
596
|
+
return inferences || [];
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const { pointFn, opts = {}, maskTransformFn } = txInfo;
|
|
600
|
+
const results = [];
|
|
601
|
+
|
|
602
|
+
for (const item of inferences) {
|
|
603
|
+
if (item.polygons) {
|
|
604
|
+
// Segmentation
|
|
605
|
+
const mfn = maskTransformFn
|
|
606
|
+
? (mask) => maskTransformFn(mask, cppBridge)
|
|
607
|
+
: null;
|
|
608
|
+
const t = await transformSegmentation(item, pointFn, { ...opts, maskTransformFn: mfn });
|
|
609
|
+
if (t) results.push(t);
|
|
610
|
+
} else if (item.raw_boxes) {
|
|
611
|
+
// Detection
|
|
612
|
+
const t = transformDetection(item, pointFn, opts);
|
|
613
|
+
if (t) results.push(t);
|
|
614
|
+
} else {
|
|
615
|
+
// Unknown format — pass through unchanged
|
|
616
|
+
results.push(deepClone(item));
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
return results;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Apply transforms for multi-image operations (concat, mosaic).
|
|
625
|
+
* @param {Array} infArrays — parallel array [infs_for_img0, infs_for_img1, ...]
|
|
626
|
+
* @param {Array|Map} transforms — array (concat) or Map<idx, tx[]> (mosaic)
|
|
627
|
+
* @param {object} cppBridge
|
|
628
|
+
* @returns {Promise<Array>} merged flat array
|
|
629
|
+
*/
|
|
630
|
+
async function applyMultiImageTransform(infArrays, transforms, cppBridge) {
|
|
631
|
+
if (!infArrays || !Array.isArray(infArrays)) return [];
|
|
632
|
+
|
|
633
|
+
const merged = [];
|
|
634
|
+
|
|
635
|
+
if (Array.isArray(transforms)) {
|
|
636
|
+
// Concat mode: transforms[i] for infArrays[i]
|
|
637
|
+
for (let i = 0; i < transforms.length; i++) {
|
|
638
|
+
const infs = infArrays[i];
|
|
639
|
+
if (!infs || !Array.isArray(infs) || infs.length === 0) continue;
|
|
640
|
+
const results = await applyTransform(infs, transforms[i], cppBridge);
|
|
641
|
+
merged.push(...results);
|
|
642
|
+
}
|
|
643
|
+
} else if (transforms instanceof Map) {
|
|
644
|
+
// Mosaic mode: transforms.get(idx) => array of txInfos
|
|
645
|
+
for (const [idx, txList] of transforms) {
|
|
646
|
+
const infs = infArrays[idx];
|
|
647
|
+
if (!infs || !Array.isArray(infs) || infs.length === 0) continue;
|
|
648
|
+
for (const tx of txList) {
|
|
649
|
+
const results = await applyTransform(infs, tx, cppBridge);
|
|
650
|
+
merged.push(...results);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
return merged;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ─── Exports ────────────────────────────────────────────────────────────────
|
|
659
|
+
|
|
660
|
+
module.exports = {
|
|
661
|
+
// Helpers
|
|
662
|
+
clipNorm,
|
|
663
|
+
transformPoints,
|
|
664
|
+
shoelaceArea,
|
|
665
|
+
reorderBoxPoints,
|
|
666
|
+
recalculateBoxFormats,
|
|
667
|
+
overlapFraction,
|
|
668
|
+
ensureRawBoxes,
|
|
669
|
+
xywhrToCorners,
|
|
670
|
+
cwhToCorners,
|
|
671
|
+
|
|
672
|
+
// Core transforms
|
|
673
|
+
transformDetection,
|
|
674
|
+
transformSegmentation,
|
|
675
|
+
|
|
676
|
+
// Per-operation transform makers
|
|
677
|
+
makeResizeTransform,
|
|
678
|
+
makeRotateTransform,
|
|
679
|
+
makeCropTransform,
|
|
680
|
+
makePaddingTransform,
|
|
681
|
+
makeConcatTransforms,
|
|
682
|
+
makeMosaicTransform,
|
|
683
|
+
makeAdvancedMosaicTransform,
|
|
684
|
+
|
|
685
|
+
// Orchestrators
|
|
686
|
+
applyTransform,
|
|
687
|
+
applyMultiImageTransform
|
|
688
|
+
};
|