@rosepetal/node-red-contrib-image-tools 1.3.2 → 1.4.0

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