@rosepetal/node-red-contrib-image-tools 1.1.3

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.
Files changed (131) hide show
  1. package/.gitattributes +6 -0
  2. package/.github/workflows/build-prebuild.yml +326 -0
  3. package/LICENSE +13 -0
  4. package/README.md +161 -0
  5. package/artifacts/darwin-arm64/package.json +25 -0
  6. package/artifacts/linux-arm64/package.json +26 -0
  7. package/artifacts/linux-x64/package.json +26 -0
  8. package/artifacts/linuxmusl-x64/package.json +26 -0
  9. package/assets/flow_time_example.gif +0 -0
  10. package/assets/nodes/io/array-in-demo.gif +0 -0
  11. package/assets/nodes/io/array-out-demo.gif +0 -0
  12. package/assets/nodes/io/array-select-demo.gif +0 -0
  13. package/assets/nodes/io/image-in-demo.gif +0 -0
  14. package/assets/nodes/mix/concat-demo.gif +0 -0
  15. package/assets/nodes/mix/mosaic-demo.gif +0 -0
  16. package/assets/nodes/transform/crop-demo.gif +0 -0
  17. package/assets/nodes/transform/filter-demo.gif +0 -0
  18. package/assets/nodes/transform/padding-demo.gif +0 -0
  19. package/assets/nodes/transform/resize-demo.gif +0 -0
  20. package/assets/nodes/transform/rotate-demo.gif +0 -0
  21. package/docs/nodes/blend/add-mask.md +275 -0
  22. package/docs/nodes/blend/add-masks.md +284 -0
  23. package/docs/nodes/blend/blend.md +248 -0
  24. package/docs/nodes/io/array-in.md +119 -0
  25. package/docs/nodes/io/array-out.md +150 -0
  26. package/docs/nodes/io/array-select.md +157 -0
  27. package/docs/nodes/io/image-in.md +131 -0
  28. package/docs/nodes/io/image-out.md +179 -0
  29. package/docs/nodes/io/queue.md +57 -0
  30. package/docs/nodes/io/save-file.md +30 -0
  31. package/docs/nodes/mix/advanced-mosaic.md +108 -0
  32. package/docs/nodes/mix/concat.md +127 -0
  33. package/docs/nodes/mix/mosaic.md +146 -0
  34. package/docs/nodes/specialized/cropBB.md +271 -0
  35. package/docs/nodes/specialized/image-align.md +426 -0
  36. package/docs/nodes/transform/crop.md +132 -0
  37. package/docs/nodes/transform/draw.md +77 -0
  38. package/docs/nodes/transform/filter.md +84 -0
  39. package/docs/nodes/transform/padding.md +133 -0
  40. package/docs/nodes/transform/resize.md +158 -0
  41. package/docs/nodes/transform/rotate.md +121 -0
  42. package/docs/nodes/util/block-detect.md +46 -0
  43. package/install.sh +144 -0
  44. package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
  45. package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
  46. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
  47. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
  48. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
  49. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
  50. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
  51. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
  52. package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
  53. package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
  54. package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
  55. package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
  56. package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
  57. package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
  58. package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
  59. package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
  60. package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
  61. package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
  62. package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
  63. package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
  64. package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
  65. package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
  66. package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
  67. package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
  68. package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
  69. package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
  70. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
  71. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
  72. package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
  73. package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
  74. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
  75. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
  76. package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
  77. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
  78. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
  79. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
  80. package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
  81. package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
  82. package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
  83. package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
  84. package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
  85. package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
  86. package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
  87. package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
  88. package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
  89. package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
  90. package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
  91. package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
  92. package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
  93. package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
  94. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
  95. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
  96. package/node-red-contrib-image-tools/package.json +64 -0
  97. package/npm/darwin-arm64/lib/.gitkeep +1 -0
  98. package/npm/darwin-arm64/package.json +25 -0
  99. package/npm/darwin-x64/lib/.gitkeep +1 -0
  100. package/npm/darwin-x64/package.json +25 -0
  101. package/npm/linux-arm64/lib/.gitkeep +1 -0
  102. package/npm/linux-arm64/package.json +26 -0
  103. package/npm/linux-x64/lib/.gitkeep +1 -0
  104. package/npm/linux-x64/package.json +26 -0
  105. package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
  106. package/npm/linuxmusl-x64/package.json +26 -0
  107. package/npm/win32-x64/lib/.gitkeep +1 -0
  108. package/npm/win32-x64/package.json +25 -0
  109. package/package.json +74 -0
  110. package/rosepetal-image-engine/binding.gyp +153 -0
  111. package/rosepetal-image-engine/package.json +19 -0
  112. package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
  113. package/rosepetal-image-engine/src/add-mask.cpp +240 -0
  114. package/rosepetal-image-engine/src/add-masks.cpp +638 -0
  115. package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
  116. package/rosepetal-image-engine/src/blend.cpp +200 -0
  117. package/rosepetal-image-engine/src/concat.cpp +329 -0
  118. package/rosepetal-image-engine/src/crop.cpp +139 -0
  119. package/rosepetal-image-engine/src/draw.cpp +414 -0
  120. package/rosepetal-image-engine/src/filter.cpp +230 -0
  121. package/rosepetal-image-engine/src/filters/kernels.h +171 -0
  122. package/rosepetal-image-engine/src/image-align.cpp +551 -0
  123. package/rosepetal-image-engine/src/main.cpp +36 -0
  124. package/rosepetal-image-engine/src/mosaic.cpp +373 -0
  125. package/rosepetal-image-engine/src/padding.cpp +124 -0
  126. package/rosepetal-image-engine/src/resize.cpp +210 -0
  127. package/rosepetal-image-engine/src/rotate.cpp +177 -0
  128. package/rosepetal-image-engine/src/utils.h +563 -0
  129. package/rosepetal-image-engine/test-formats.js +119 -0
  130. package/scripts/build-opencv-static.ps1 +166 -0
  131. package/scripts/build-opencv-static.sh +147 -0
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Node-RED logic for *rosepetal-mosaic* (Ultra-optimized C++ backend).
3
+ * Creates composite images by placing multiple images on a canvas at specified positions.
4
+ * Super fast with zero-copy operations and parallel processing.
5
+ */
6
+ const { performance } = require('perf_hooks');
7
+ const CppProcessor = require('../../lib/cpp-bridge.js');
8
+
9
+ module.exports = function (RED) {
10
+ const NodeUtils = require('../../lib/node-utils.js')(RED);
11
+
12
+ function MosaicNode(config) {
13
+ RED.nodes.createNode(this, config);
14
+ const node = this;
15
+
16
+ node.on('input', async (msg, send, done) => {
17
+ try {
18
+ const t0 = performance.now();
19
+ node.status({});
20
+
21
+ /* I/O paths */
22
+ const inputPath = config.inputPath || 'payload';
23
+ const outputPath = config.outputPath || 'payload';
24
+ const outputFormat = config.outputFormat || 'raw';
25
+ const outputQuality = parseInt(config.outputQuality) || 90;
26
+ const pngOptimize = config.pngOptimize || false;
27
+
28
+ /* Canvas configuration */
29
+ const canvasWidth = Number(NodeUtils.resolveDimension(node, config.canvasWidthType, config.canvasWidth, msg));
30
+ const canvasHeight = Number(NodeUtils.resolveDimension(node, config.canvasHeightType, config.canvasHeight, msg));
31
+ const backgroundColor = config.backgroundColor || '#000000';
32
+ const normalized = !!config.coordNorm;
33
+
34
+ /* Position mappings */
35
+ const positions = config.positions || [];
36
+
37
+ /* Input images array */
38
+ const inputImages = RED.util.getMessageProperty(msg, inputPath);
39
+ const imageArray = Array.isArray(inputImages) ? inputImages : [inputImages];
40
+
41
+ // Capture first image for error passthrough
42
+ const firstImage = imageArray[0];
43
+
44
+ // Validate input images - mosaic expects array input
45
+ if (!NodeUtils.validateListImage(imageArray, node)) {
46
+ return NodeUtils.handleValidationErrorWithPassthrough(
47
+ node, 'Invalid image list', msg, send, done,
48
+ { originalPayload: firstImage, outputPath, outputType: 'single' }
49
+ );
50
+ }
51
+
52
+ /* Validate positions - allow empty positions to show just background canvas */
53
+ const validPositions = positions.filter(pos => {
54
+ const arrayIndex = parseInt(pos.arrayIndex);
55
+ return arrayIndex >= 0 && arrayIndex < imageArray.length;
56
+ });
57
+
58
+ // Note: Allow empty validPositions - this will create canvas with just background color
59
+
60
+ /* Validate canvas dimensions */
61
+ if (canvasWidth <= 0 || canvasHeight <= 0) {
62
+ throw new Error('Canvas dimensions must be positive numbers');
63
+ }
64
+
65
+ /* Single ultra-fast C++ call */
66
+ const { image, timing = {} } = await CppProcessor.mosaic(
67
+ imageArray,
68
+ canvasWidth,
69
+ canvasHeight,
70
+ backgroundColor,
71
+ validPositions,
72
+ normalized,
73
+ outputFormat,
74
+ outputQuality,
75
+ pngOptimize
76
+ );
77
+
78
+ /* Set output */
79
+ RED.util.setMessageProperty(msg, outputPath, image);
80
+
81
+ /* Performance status - same format as other nodes */
82
+ const { convertMs = 0, taskMs = 0, encodeMs = 0 } = timing;
83
+ const totalTime = performance.now() - t0;
84
+
85
+ // Debug image display
86
+ let debugFormat = null;
87
+ if (config.debugEnabled) {
88
+ try {
89
+ // Resolve and validate debug width
90
+ let debugWidth = NodeUtils.resolveDimension(
91
+ node,
92
+ config.debugWidthType,
93
+ config.debugWidth,
94
+ msg
95
+ );
96
+ debugWidth = Math.max(1, parseInt(debugWidth) || 200); // Ensure positive, default 200
97
+
98
+ const debugResult = await NodeUtils.debugImageDisplay(
99
+ image,
100
+ outputFormat,
101
+ outputQuality,
102
+ node,
103
+ true,
104
+ debugWidth
105
+ );
106
+
107
+ if (debugResult) {
108
+ debugFormat = debugResult.formatMessage;
109
+ // Update node status with debug info
110
+ const positionsText = validPositions.length === 0 ? 'empty canvas' : `${validPositions.length} pos`;
111
+ NodeUtils.setSuccessStatusWithDebug(node, 1, totalTime, {
112
+ convertMs: convertMs,
113
+ taskMs: taskMs,
114
+ encodeMs: encodeMs
115
+ }, `${debugFormat} (${positionsText})`);
116
+ }
117
+ } catch (debugError) {
118
+ node.warn(`Debug display error: ${debugError.message}`);
119
+ }
120
+ }
121
+
122
+ // Set regular status if debug not enabled or failed
123
+ if (!debugFormat) {
124
+ const statusText = validPositions.length === 0
125
+ ? `OK: empty canvas in ${totalTime.toFixed(2)} ms`
126
+ : `OK: ${validPositions.length} pos in ${totalTime.toFixed(2)} ms ` +
127
+ `(conv ${(convertMs + encodeMs).toFixed(2)} ms | ` +
128
+ `task ${taskMs.toFixed(2)} ms)`;
129
+
130
+ node.status({
131
+ fill: 'green',
132
+ shape: 'dot',
133
+ text: statusText
134
+ });
135
+ }
136
+
137
+ NodeUtils.recordPerformanceMetrics(node, msg, timing, totalTime);
138
+
139
+ send(msg);
140
+ done && done();
141
+ } catch (err) {
142
+ NodeUtils.handleNodeErrorWithPassthrough(
143
+ node, err, msg, send, done, 'mosaic processing',
144
+ { originalPayload: firstImage, outputPath, outputType: 'single' }
145
+ );
146
+ }
147
+ });
148
+ }
149
+
150
+ RED.nodes.registerType('mosaic', MosaicNode);
151
+ };
@@ -0,0 +1,268 @@
1
+ <!-- ───────── nodes/io/cropBB.html (Crop Bounding Boxes Node) ────────────── -->
2
+
3
+ <!-- 1 ▸ Runtime registration -->
4
+ <script type="text/javascript">
5
+ RED.nodes.registerType('cropBB',{
6
+
7
+ category:'RP Image',
8
+ color :'#FF6B35', // Distinct orange color to differentiate from standard pink
9
+ icon :'font-awesome/fa-scissors',
10
+
11
+ defaults:{
12
+ name:{value:""},
13
+ imageInputPath:{value:"image"}, imageInputPathType:{value:"msg"},
14
+ bboxInputPath:{value:"default"}, bboxInputPathType:{value:"msg"},
15
+ outputPath:{value:"payload"}, outputPathType:{value:"msg"},
16
+ outputFormat:{value:"raw"},
17
+ outputQuality:{value:90},
18
+ pngOptimize:{value:false},
19
+
20
+ // Filtering options
21
+ minConfidence:{value:0.5},
22
+ minConfidenceType:{value:"num"},
23
+
24
+ // Debug configuration
25
+ debugEnabled:{value:false},
26
+ debugWidth:{value:200},
27
+ debugWidthType:{value:"num"}
28
+ },
29
+
30
+ inputs:1, outputs:1,
31
+ label:function(){ return this.name || "cropBB"; },
32
+
33
+ /* ---------------- oneditprepare ---------------- */
34
+ oneditprepare:function(){
35
+
36
+ /* I/O typedInputs */
37
+ $("#node-input-imageInputPath").typedInput({
38
+ default:'msg',types:['msg','flow','global'],
39
+ typeField:"#node-input-imageInputPathType"
40
+ });
41
+
42
+ $("#node-input-bboxInputPath").typedInput({
43
+ default:'msg',types:['msg','flow','global'],
44
+ typeField:"#node-input-bboxInputPathType"
45
+ });
46
+
47
+ $("#node-input-outputPath").typedInput({
48
+ default:'msg',types:['msg','flow','global'],
49
+ typeField:"#node-input-outputPathType"
50
+ });
51
+
52
+ /* confidence threshold */
53
+ $("#node-input-minConfidence").typedInput({
54
+ default:'num',
55
+ types:['num','msg','flow','global'],
56
+ typeField:"#node-input-minConfidenceType"
57
+ });
58
+
59
+ /* debug width */
60
+ $("#node-input-debugWidth").typedInput({
61
+ default:'num',
62
+ types:['num','msg','flow','global'],
63
+ typeField:"#node-input-debugWidthType"
64
+ });
65
+
66
+ /* Quality visibility logic */
67
+ function updateQualityVisibility() {
68
+ const format = $('#node-input-outputFormat').val();
69
+ if (format === 'jpg' || format === 'webp') {
70
+ $('#quality-row').show();
71
+ } else {
72
+ $('#quality-row').hide();
73
+ }
74
+ $('#png-optimize-row').toggle(format === 'png');
75
+ }
76
+
77
+ $('#node-input-outputFormat').on('change', updateQualityVisibility);
78
+ updateQualityVisibility(); // Initial call
79
+
80
+ /* Debug visibility logic */
81
+ function updateDebugWidthVisibility() {
82
+ if ($('#node-input-debugEnabled').is(':checked')) {
83
+ $('#debug-width-row').show();
84
+ } else {
85
+ $('#debug-width-row').hide();
86
+ }
87
+ }
88
+
89
+ $('#node-input-debugEnabled').on('change', updateDebugWidthVisibility);
90
+ updateDebugWidthVisibility(); // Initial call
91
+ }
92
+ });
93
+ </script>
94
+
95
+ <!-- 2 ▸ Edit template -->
96
+ <script type="text/html" data-template-name="cropBB">
97
+ <div class="form-row">
98
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
99
+ <input type="text" id="node-input-name" placeholder="Name">
100
+ </div>
101
+
102
+ <hr>
103
+
104
+ <!-- I/O Section -->
105
+ <div class="form-row">
106
+ <label for="node-input-imageInputPath"><i class="fa fa-sign-in"></i> Input from</label>
107
+ <input type="text" id="node-input-imageInputPath" style="width: 70%;">
108
+ <input type="hidden" id="node-input-imageInputPathType">
109
+ </div>
110
+ <div class="form-row">
111
+ <label for="node-input-bboxInputPath"><i class="fa fa-square-o"></i> Bounding Boxes</label>
112
+ <input type="text" id="node-input-bboxInputPath" style="width: 70%;">
113
+ <input type="hidden" id="node-input-bboxInputPathType">
114
+ </div>
115
+ <div class="form-row">
116
+ <label for="node-input-outputPath"><i class="fa fa-sign-out"></i> Output to</label>
117
+ <input type="text" id="node-input-outputPath" style="width: 70%;">
118
+ <input type="hidden" id="node-input-outputPathType">
119
+ </div>
120
+ <div class="form-row">
121
+ <label for="node-input-outputFormat"><i class="fa fa-file-image-o"></i> Output Format</label>
122
+ <select id="node-input-outputFormat" style="width: 200px;">
123
+ <option value="raw">Raw (fastest)</option>
124
+ <option value="jpg">JPEG</option>
125
+ <option value="png">PNG</option>
126
+ <option value="webp">WebP</option>
127
+ </select>
128
+ </div>
129
+ <div class="form-row" id="quality-row">
130
+ <label for="node-input-outputQuality"><i class="fa fa-sliders"></i> Quality</label>
131
+ <input type="number" id="node-input-outputQuality" min="1" max="100" value="90" style="width: 70px;">
132
+ <span style="margin-left: 10px; color: #666;">1-100 (JPG/WebP only)</span>
133
+ </div>
134
+
135
+ <div class="form-row" id="png-optimize-row" style="display: none;">
136
+ <label for="node-input-pngOptimize"><i class="fa fa-compress"></i> PNG Optimize</label>
137
+ <input type="checkbox" id="node-input-pngOptimize" style="display:inline-block; width:auto; vertical-align:baseline;">
138
+ <label for="node-input-pngOptimize" style="width:auto; margin-left:5px;">Compress PNG (slower, smaller file)</label>
139
+ </div>
140
+
141
+ <!-- Debug Configuration -->
142
+ <div class="form-row">
143
+ <label for="node-input-debugEnabled"><i class="fa fa-bug"></i> Debug</label>
144
+ <input type="checkbox" id="node-input-debugEnabled" style="display:inline-block; width:auto; vertical-align:baseline;">
145
+ <label for="node-input-debugEnabled" style="width:auto; margin-left:5px;">Show processed image</label>
146
+ </div>
147
+ <div class="form-row" id="debug-width-row" style="display: none;">
148
+ <label for="node-input-debugWidth"><i class="fa fa-arrows-h"></i> Debug Width</label>
149
+ <input type="text" id="node-input-debugWidth" style="width: 120px;">
150
+ <input type="hidden" id="node-input-debugWidthType">
151
+ <span style="margin-left: 10px; color: #666;">pixels</span>
152
+ </div>
153
+
154
+ <hr>
155
+
156
+ <!-- CropBB Specific Options -->
157
+ <div class="form-row">
158
+ <label for="node-input-minConfidence"><i class="fa fa-filter"></i> Min Confidence</label>
159
+ <input type="text" id="node-input-minConfidence" style="width: 70%;">
160
+ <input type="hidden" id="node-input-minConfidenceType">
161
+ </div>
162
+
163
+ </script>
164
+
165
+ <!-- 3 ▸ Help documentation -->
166
+ <script type="text/html" data-help-name="cropBB">
167
+ <p>Extracts image crops from bounding boxes detected by inference models.</p>
168
+
169
+ <h3>Details</h3>
170
+ <p>This node takes images and their corresponding bounding box data (typically from an inferencer node)
171
+ and extracts each detected region as a separate image crop. Each crop is paired with its detection metadata.</p>
172
+
173
+ <h3>Inputs</h3>
174
+ <dl class="message-properties">
175
+ <dt>Image Input<span class="property-type">image | image[]</span></dt>
176
+ <dd>Single image or array of images in standard Rosepetal format</dd>
177
+
178
+ <dt>Bounding Boxes<span class="property-type">array</span></dt>
179
+ <dd>Array of detection objects with format: <code>[{raw_boxes: [[x1,y1],...], tag: "label", confidence: 0.95}, ...]</code></dd>
180
+ </dl>
181
+
182
+ <h3>Outputs</h3>
183
+ <dl class="message-properties">
184
+ <dt>crops<span class="property-type">array</span></dt>
185
+ <dd>Array of image objects with metadata. Each element is directly usable as an image with added <code>tag</code>, <code>confidence</code>, and <code>bbox</code> properties.</dd>
186
+ </dl>
187
+
188
+ <h3>Configuration</h3>
189
+ <dl class="message-properties">
190
+ <dt>Image Input</dt>
191
+ <dd>Path to image data (default: <code>msg.image</code>)</dd>
192
+
193
+ <dt>Bounding Boxes</dt>
194
+ <dd>Path to inference results (default: <code>msg.default</code>)</dd>
195
+
196
+ <dt>Output Format</dt>
197
+ <dd>Raw (fastest), JPEG, PNG, or WebP encoding</dd>
198
+
199
+ <dt>Min Confidence</dt>
200
+ <dd>Filter out detections below this confidence threshold (0.0-1.0)</dd>
201
+
202
+ <dt>Debug</dt>
203
+ <dd>Enable debug image display in Node-RED editor</dd>
204
+ </dl>
205
+
206
+ <h3>Example Input (Bounding Boxes)</h3>
207
+ <pre>[
208
+ {
209
+ "raw_boxes": [[0.1, 0.2], [0.4, 0.2], [0.4, 0.6], [0.1, 0.6]],
210
+ "tag": "mountain",
211
+ "confidence": 0.98095703125
212
+ },
213
+ {
214
+ "raw_boxes": [[0.5, 0.1], [0.9, 0.1], [0.9, 0.4], [0.5, 0.4]],
215
+ "tag": "sky",
216
+ "confidence": 0.92
217
+ }
218
+ ]</pre>
219
+
220
+ <h3>Example Output</h3>
221
+ <pre>[
222
+ {
223
+ data: Buffer, // Crop image data
224
+ width: 150,
225
+ height: 200,
226
+ channels: 3,
227
+ colorSpace: "RGB",
228
+ dtype: "uint8",
229
+ tag: "mountain", // Detection label
230
+ confidence: 0.98, // Detection confidence
231
+ bbox: { // Crop coordinates in pixels
232
+ x: 100, y: 50, width: 150, height: 200,
233
+ normalized: {x1: 0.1, y1: 0.2, x2: 0.4, y2: 0.6}
234
+ }
235
+ },
236
+ {
237
+ data: Buffer,
238
+ width: 80,
239
+ height: 120,
240
+ channels: 3,
241
+ colorSpace: "RGB",
242
+ dtype: "uint8",
243
+ tag: "sky",
244
+ confidence: 0.92,
245
+ bbox: {
246
+ x: 300, y: 200, width: 80, height: 120,
247
+ normalized: {x1: 0.5, y1: 0.1, x2: 0.9, y2: 0.4}
248
+ }
249
+ }
250
+ ]</pre>
251
+
252
+ <h3>Usage</h3>
253
+ <p>Each array element can be directly used as an image input to other nodes:</p>
254
+ <pre>// Access first crop directly
255
+ msg.payload[0] // {data, width, height, channels, colorSpace, tag, confidence, bbox}
256
+
257
+ // Use in image-out node
258
+ msg.payload = crops[0]; // No need for crops[0].crop
259
+
260
+ // Filter by tag
261
+ const mountains = crops.filter(c => c.tag === "mountain");
262
+
263
+ // Sort by confidence
264
+ crops.sort((a, b) => b.confidence - a.confidence);</pre>
265
+
266
+ <h3>Performance</h3>
267
+ <p>Uses optimized C++ backend for fast crop extraction. Multiple crops are processed in parallel for best performance.</p>
268
+ </script>
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Node-RED logic for cropBB (Crop Bounding Boxes)
3
+ * Extracts image crops from bounding box detection results
4
+ * @author Rosepetal
5
+ */
6
+ const { performance } = require('perf_hooks');
7
+ const CppProcessor = require('../../lib/cpp-bridge.js');
8
+
9
+ module.exports = function (RED) {
10
+ const NodeUtils = require('../../lib/node-utils.js')(RED);
11
+
12
+ function CropBBNode(config) {
13
+ RED.nodes.createNode(this, config);
14
+ const node = this;
15
+
16
+ node.on('input', async (msg, send, done) => {
17
+ /* Output path - captured early for error passthrough */
18
+ const outputPath = config.outputPath || 'payload';
19
+
20
+ try {
21
+ const t0 = performance.now();
22
+ node.status({});
23
+
24
+ /* Input/Output paths */
25
+ const imageInputPath = config.imageInputPath || 'images';
26
+ const bboxInputPath = config.bboxInputPath || 'default';
27
+
28
+ /* Configuration */
29
+ const outputFormat = config.outputFormat || 'raw';
30
+ const outputQuality = parseInt(config.outputQuality) || 90;
31
+ const pngOptimize = config.pngOptimize || false;
32
+ const minConfidence = NodeUtils.resolveDimension(node, config.minConfidenceType, config.minConfidence, msg) || 0.5;
33
+
34
+ /* Get input data */
35
+ const imageData = RED.util.getMessageProperty(msg, imageInputPath);
36
+ const bboxData = RED.util.getMessageProperty(msg, bboxInputPath);
37
+
38
+ if (!imageData) {
39
+ return NodeUtils.handleValidationErrorWithPassthrough(
40
+ node, `No image data found at ${imageInputPath}`, msg, send, done,
41
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
42
+ );
43
+ }
44
+
45
+ if (!bboxData) {
46
+ return NodeUtils.handleValidationErrorWithPassthrough(
47
+ node, `No bounding box data found at ${bboxInputPath}`, msg, send, done,
48
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
49
+ );
50
+ }
51
+
52
+ /* Handle single image vs array */
53
+ const images = Array.isArray(imageData) ? imageData : [imageData];
54
+
55
+ // The bboxData should be an array of detection objects
56
+ if (!bboxData || !Array.isArray(bboxData)) {
57
+ return NodeUtils.handleValidationErrorWithPassthrough(
58
+ node, `Invalid bounding box data structure. Expected array at ${bboxInputPath}`, msg, send, done,
59
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
60
+ );
61
+ }
62
+
63
+ const detections = bboxData;
64
+
65
+ // Validate input images
66
+ if (Array.isArray(imageData)) {
67
+ if (!NodeUtils.validateListImage(imageData, node)) {
68
+ return NodeUtils.handleValidationErrorWithPassthrough(
69
+ node, 'Invalid image list structure', msg, send, done,
70
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
71
+ );
72
+ }
73
+ } else {
74
+ if (!NodeUtils.validateSingleImage(imageData, node)) {
75
+ return NodeUtils.handleValidationErrorWithPassthrough(
76
+ node, 'Invalid image structure', msg, send, done,
77
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
78
+ );
79
+ }
80
+ }
81
+
82
+ /* Process each image with the detections */
83
+ const allCrops = [];
84
+ let totalConvertMs = 0, totalTaskMs = 0, totalEncodeMs = 0;
85
+
86
+ // For now, assume single image with all detections
87
+ // In the future, could handle multiple images with detection arrays
88
+ const image = images[0]; // Use first image
89
+
90
+ /* Filter detections by confidence and extract bounding boxes */
91
+ const validBboxes = [];
92
+ for (const detection of detections) {
93
+ const bbox = parseSingleDetection(detection, minConfidence, image, node);
94
+ if (bbox) {
95
+ validBboxes.push(bbox);
96
+ }
97
+ }
98
+
99
+ if (validBboxes.length === 0) {
100
+ node.warn(`No valid bounding boxes found with confidence >= ${minConfidence}`);
101
+ RED.util.setMessageProperty(msg, outputPath, []);
102
+ const elapsed = performance.now() - t0;
103
+ NodeUtils.recordPerformanceMetrics(node, msg, {
104
+ convertMs: 0,
105
+ encodeMs: 0,
106
+ taskMs: 0
107
+ }, elapsed);
108
+ send(msg);
109
+ if (done) done();
110
+ return;
111
+ }
112
+
113
+ /* Create crop jobs for all valid bounding boxes */
114
+ const cropJobs = validBboxes.map(bbox => {
115
+ // Convert bbox coordinates to crop parameters
116
+ const { x, y, width, height, label, confidence, originalBbox } = bbox;
117
+
118
+ return CppProcessor.crop(image, x, y, width, height, false, outputFormat, outputQuality, pngOptimize)
119
+ .then(result => ({
120
+ ...result.image, // Spread image properties (data, width, height, channels, colorSpace, dtype)
121
+ tag: label, // Add tag metadata directly
122
+ confidence: confidence, // Add confidence metadata directly
123
+ bbox: originalBbox, // Add bbox metadata directly
124
+ timing: result.timing
125
+ }));
126
+ });
127
+
128
+ /* Execute all crops in parallel */
129
+ const cropResults = await Promise.all(cropJobs);
130
+
131
+ /* Accumulate results and timing */
132
+ cropResults.forEach(result => {
133
+ // Extract timing before pushing to output
134
+ totalConvertMs += result.timing?.convertMs ?? 0;
135
+ totalTaskMs += result.timing?.taskMs ?? 0;
136
+ totalEncodeMs += result.timing?.encodeMs ?? 0;
137
+
138
+ // Remove timing property and push flattened image with metadata
139
+ const { timing, ...cropWithMetadata } = result;
140
+ allCrops.push(cropWithMetadata);
141
+ });
142
+
143
+ /* Set output */
144
+ RED.util.setMessageProperty(msg, outputPath, allCrops);
145
+
146
+ /* Status and timing */
147
+ const totalTime = performance.now() - t0;
148
+
149
+ // Debug image display for first crop if enabled
150
+ let debugFormat = null;
151
+ if (config.debugEnabled && allCrops.length > 0) {
152
+ try {
153
+ let debugWidth = NodeUtils.resolveDimension(node, config.debugWidthType, config.debugWidth, msg) || 200;
154
+ debugWidth = Math.max(1, parseInt(debugWidth));
155
+
156
+ const debugResult = await NodeUtils.debugImageDisplay(
157
+ allCrops[0], // First crop is now directly the image object
158
+ outputFormat,
159
+ outputQuality,
160
+ node,
161
+ true,
162
+ debugWidth
163
+ );
164
+
165
+ if (debugResult) {
166
+ debugFormat = `${debugResult.formatMessage} (${debugResult.size}B)`;
167
+ }
168
+ } catch (debugError) {
169
+ node.warn(`Debug display error: ${debugError.message}`);
170
+ }
171
+ }
172
+
173
+ NodeUtils.setSuccessStatusWithDebug(
174
+ node,
175
+ allCrops.length,
176
+ totalTime,
177
+ { convertMs: totalConvertMs, taskMs: totalTaskMs, encodeMs: totalEncodeMs },
178
+ debugFormat
179
+ );
180
+
181
+ NodeUtils.recordPerformanceMetrics(node, msg, {
182
+ convertMs: totalConvertMs,
183
+ encodeMs: totalEncodeMs,
184
+ taskMs: totalTaskMs
185
+ }, totalTime);
186
+
187
+ send(msg);
188
+ if (done) done();
189
+
190
+ } catch (err) {
191
+ NodeUtils.handleNodeErrorWithPassthrough(
192
+ node, err, msg, send, done, 'cropBB processing',
193
+ { originalPayload: [], outputPath, outputType: 'empty-array' }
194
+ );
195
+ }
196
+ });
197
+ }
198
+
199
+ /**
200
+ * Parse a single detection object into standardized bbox format
201
+ * Handles the format:
202
+ * {
203
+ * "raw_boxes": [[x1,y1], [x2,y1], [x2,y2], [x1,y2]], // normalized 0-1 coordinates
204
+ * "confidence": 0.97,
205
+ * "tag": "mountain"
206
+ * }
207
+ */
208
+ function parseSingleDetection(det, minConfidence, image, node) {
209
+ if (!det || typeof det !== 'object') return null;
210
+
211
+ // Extract confidence
212
+ const confidence = det.confidence || 1.0;
213
+ if (confidence < minConfidence) return null;
214
+
215
+ // Extract tag
216
+ const label = det.tag || 'unknown';
217
+
218
+ // Extract coordinates from 4-corner format
219
+ if (!det.raw_boxes || !Array.isArray(det.raw_boxes) || det.raw_boxes.length !== 4) {
220
+ node.warn(`Invalid raw_boxes format in detection: expected 4 corner points, got ${det.raw_boxes}`);
221
+ return null;
222
+ }
223
+
224
+ try {
225
+ // Parse 4 corner points: [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
226
+ const [[x1, y1], [x2, y1_check], [x2_check, y2], [x1_check, y2_check]] = det.raw_boxes;
227
+
228
+ // Validate corner format consistency
229
+ if (x2 !== x2_check || x1 !== x1_check || y1 !== y1_check || y2 !== y2_check) {
230
+ node.warn(`Inconsistent corner points in detection raw_boxes: ${JSON.stringify(det.raw_boxes)}`);
231
+ return null;
232
+ }
233
+
234
+ // Coordinates are normalized (0-1), convert to pixels
235
+ const imageWidth = image.width;
236
+ const imageHeight = image.height;
237
+
238
+ const x = Math.round(x1 * imageWidth);
239
+ const y = Math.round(y1 * imageHeight);
240
+ const width = Math.round((x2 - x1) * imageWidth);
241
+ const height = Math.round((y2 - y1) * imageHeight);
242
+
243
+ // Validate pixel coordinates
244
+ if (width <= 0 || height <= 0) {
245
+ node.warn(`Invalid dimensions: width=${width}, height=${height} for raw_boxes ${JSON.stringify(det.raw_boxes)}`);
246
+ return null;
247
+ }
248
+
249
+ // Ensure coordinates are within image bounds
250
+ const clippedX = Math.max(0, Math.min(x, imageWidth - 1));
251
+ const clippedY = Math.max(0, Math.min(y, imageHeight - 1));
252
+ const clippedWidth = Math.min(width, imageWidth - clippedX);
253
+ const clippedHeight = Math.min(height, imageHeight - clippedY);
254
+
255
+ return {
256
+ x: clippedX,
257
+ y: clippedY,
258
+ width: clippedWidth,
259
+ height: clippedHeight,
260
+ label: String(label),
261
+ confidence: Number(confidence),
262
+ originalBbox: {
263
+ x: clippedX,
264
+ y: clippedY,
265
+ width: clippedWidth,
266
+ height: clippedHeight,
267
+ normalized: { x1, y1, x2, y2 }
268
+ }
269
+ };
270
+ } catch (error) {
271
+ node.warn(`Error parsing detection box: ${error.message}`);
272
+ return null;
273
+ }
274
+ }
275
+
276
+ RED.nodes.registerType("cropBB", CropBBNode);
277
+ };