@rosepetal/node-red-contrib-image-tools 1.6.3 → 1.7.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.
Files changed (60) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/README.md +2 -0
  3. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  4. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  5. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  6. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +11 -4
  7. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +11 -4
  8. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +11 -4
  9. package/node-red-contrib-image-tools/nodes/blend/blend.html +11 -4
  10. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  11. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  12. package/node-red-contrib-image-tools/nodes/io/image-out.html +11 -4
  13. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  14. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +11 -4
  15. package/node-red-contrib-image-tools/nodes/mix/concat.html +11 -4
  16. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +11 -4
  17. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  18. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  19. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +3 -2
  20. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +3 -3
  21. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  22. package/node-red-contrib-image-tools/nodes/transform/crop.html +11 -4
  23. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  24. package/node-red-contrib-image-tools/nodes/transform/filter.html +11 -4
  25. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  26. package/node-red-contrib-image-tools/nodes/transform/padding.html +11 -4
  27. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  28. package/node-red-contrib-image-tools/nodes/transform/resize.html +3 -3
  29. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  30. package/node-red-contrib-image-tools/nodes/transform/rotate.html +11 -4
  31. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  32. package/npm/darwin-arm64/package.json +1 -1
  33. package/npm/darwin-x64/package.json +1 -1
  34. package/npm/linux-arm64/package.json +1 -1
  35. package/npm/linux-x64/package.json +1 -1
  36. package/npm/linuxmusl-x64/package.json +1 -1
  37. package/npm/win32-x64/package.json +1 -1
  38. package/package.json +6 -6
  39. package/rosepetal-image-engine/binding.gyp +2 -1
  40. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  41. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  42. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  43. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  44. package/rosepetal-image-engine/src/blend.cpp +34 -20
  45. package/rosepetal-image-engine/src/codec.cpp +157 -0
  46. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  47. package/rosepetal-image-engine/src/concat.cpp +38 -43
  48. package/rosepetal-image-engine/src/crop.cpp +23 -26
  49. package/rosepetal-image-engine/src/draw.cpp +33 -10
  50. package/rosepetal-image-engine/src/filter.cpp +22 -26
  51. package/rosepetal-image-engine/src/heat-diff.cpp +31 -8
  52. package/rosepetal-image-engine/src/image-align.cpp +36 -32
  53. package/rosepetal-image-engine/src/main.cpp +4 -0
  54. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  55. package/rosepetal-image-engine/src/padding.cpp +30 -29
  56. package/rosepetal-image-engine/src/resize.cpp +20 -25
  57. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  58. package/rosepetal-image-engine/src/utils.h +243 -144
  59. package/scripts/dual-register.js +32 -25
  60. package/scripts/sync-version.js +58 -41
@@ -93,9 +93,9 @@ module.exports = function (RED) {
93
93
  });
94
94
 
95
95
  if (useSharpWebp) {
96
- for (let i = 0; i < outImgs.length; i++) {
97
- outImgs[i] = await NodeUtils.encodeWebpAdvanced(outImgs[i], cfg);
98
- }
96
+ // Encode all images concurrently (Sharp runs on the libuv thread pool)
97
+ const webps = await Promise.all(outImgs.map((img) => NodeUtils.encodeWebpAdvanced(img, cfg)));
98
+ webps.forEach((webp, i) => { outImgs[i] = webp; });
99
99
  }
100
100
 
101
101
  NodeUtils.setOutputValue(node, msg, outPath, outputPathType, Array.isArray(originalPayload) ? outImgs : outImgs[0]);
@@ -220,9 +220,9 @@
220
220
  const debugWidth = data.debugWidth || 200;
221
221
  const debugHeight = data.debugHeight || 200;
222
222
 
223
- // Apply reasonable maximum limits (500px max width)
224
- const maxDisplayWidth = Math.min(debugWidth, 500);
225
- const displayHeight = debugHeight * (maxDisplayWidth / debugWidth);
223
+ // Display at the server-resized debug dimensions (no display cap)
224
+ const maxDisplayWidth = debugWidth;
225
+ const displayHeight = debugHeight;
226
226
 
227
227
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
228
228
 
@@ -116,9 +116,9 @@ module.exports = function (RED) {
116
116
  );
117
117
 
118
118
  if (useSharpWebp) {
119
- for (let i = 0; i < images.length; i++) {
120
- images[i] = await NodeUtils.encodeWebpAdvanced(images[i], config);
121
- }
119
+ // Encode all images concurrently (Sharp runs on the libuv thread pool)
120
+ const webps = await Promise.all(images.map((img) => NodeUtils.encodeWebpAdvanced(img, config)));
121
+ webps.forEach((webp, i) => { images[i] = webp; });
122
122
  }
123
123
 
124
124
  const out = Array.isArray(originalPayload) ? images : images[0];
@@ -136,6 +136,10 @@
136
136
 
137
137
  const nodeElement = document.getElementById(nodeId);
138
138
  if (!nodeElement) return;
139
+
140
+ // Size to the server-resized debug image (no display cap)
141
+ var debugWidth = data.debugWidth || 200;
142
+ var debugHeight = data.debugHeight || 200;
139
143
 
140
144
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
141
145
 
@@ -145,8 +149,8 @@
145
149
  debugContainer.id = 'debug-img-container-' + nodeId;
146
150
  debugContainer.setAttribute('x', '70');
147
151
  debugContainer.setAttribute('y', '5');
148
- debugContainer.setAttribute('width', '120');
149
- debugContainer.setAttribute('height', '120');
152
+ debugContainer.setAttribute('width', debugWidth.toString());
153
+ debugContainer.setAttribute('height', debugHeight.toString());
150
154
  debugContainer.style.overflow = 'visible';
151
155
 
152
156
  // Create simple image directly inside foreignObject
@@ -156,8 +160,8 @@
156
160
  img.style.height = 'auto';
157
161
  img.style.display = 'block';
158
162
  img.style.cursor = 'pointer';
159
- img.style.maxHeight = '100px';
160
- img.style.maxWidth = '100px';
163
+ img.style.maxHeight = 'none';
164
+ img.style.maxWidth = 'none';
161
165
 
162
166
  img.onclick = function() {
163
167
  removeDebugImage(nodeId);
@@ -165,6 +169,9 @@
165
169
 
166
170
  debugContainer.appendChild(img);
167
171
  nodeElement.appendChild(debugContainer);
172
+ } else {
173
+ debugContainer.setAttribute('width', debugWidth.toString());
174
+ debugContainer.setAttribute('height', debugHeight.toString());
168
175
  }
169
176
 
170
177
  const img = document.getElementById('debug-img-' + nodeId);
@@ -87,9 +87,9 @@ module.exports = function (RED) {
87
87
  }, { totalConvertMs: 0, totalTaskMs: 0, encodeMs: 0, images: [] });
88
88
 
89
89
  if (useSharpWebp) {
90
- for (let i = 0; i < images.length; i++) {
91
- images[i] = await NodeUtils.encodeWebpAdvanced(images[i], config);
92
- }
90
+ // Encode all images concurrently (Sharp runs on the libuv thread pool)
91
+ const webps = await Promise.all(images.map((img) => NodeUtils.encodeWebpAdvanced(img, config)));
92
+ webps.forEach((webp, i) => { images[i] = webp; });
93
93
  }
94
94
 
95
95
  const out = Array.isArray(originalPayload) ? images : images[0];
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-darwin-arm64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt native binary for macOS ARM64 (Apple Silicon)",
5
5
  "os": ["darwin"],
6
6
  "cpu": ["arm64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-darwin-x64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt native binary for macOS x64 (Intel)",
5
5
  "os": ["darwin"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linux-arm64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt native binary for Linux ARM64 (glibc)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["arm64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linux-x64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt native binary for Linux x64 (glibc)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt native binary for Linux x64 (musl/Alpine)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/rosepetal-engine-win32-x64",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Prebuilt rosepetal-image-engine binary for Windows x64",
5
5
  "os": ["win32"],
6
6
  "cpu": ["x64"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools",
3
- "version": "1.6.3",
3
+ "version": "1.7.0",
4
4
  "description": "Node-RED Image Processing Toolkit",
5
5
  "main": "install.sh",
6
6
  "directories": {
@@ -36,11 +36,11 @@
36
36
  "sharp": "^0.34.2"
37
37
  },
38
38
  "optionalDependencies": {
39
- "@rosepetal/node-red-contrib-image-tools-linux-x64": "1.6.3",
40
- "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.6.3",
41
- "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.6.3",
42
- "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.6.3",
43
- "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.6.3"
39
+ "@rosepetal/node-red-contrib-image-tools-linux-x64": "1.7.0",
40
+ "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.7.0",
41
+ "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.7.0",
42
+ "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.7.0",
43
+ "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.7.0"
44
44
  },
45
45
  "node-red": {
46
46
  "version": ">=1.0.0",
@@ -23,7 +23,8 @@
23
23
  "src/image-align.cpp",
24
24
  "src/draw.cpp",
25
25
  "src/color-convert.cpp",
26
- "src/heat-diff.cpp"
26
+ "src/heat-diff.cpp",
27
+ "src/codec.cpp"
27
28
  ],
28
29
  "defines": [
29
30
  "NAPI_CPP_EXCEPTIONS"
@@ -44,29 +44,8 @@ inline cv::Vec3f GenerateMaximallyDifferentColor(
44
44
  return firstColor;
45
45
  }
46
46
 
47
- // Generate candidate colors evenly distributed in HSV space
48
- std::vector<cv::Vec3f> candidates;
49
- const int numHues = 24; // Every 15 degrees
50
- const int numSaturations = 3; // 60%, 80%, 100%
51
- const int numValues = 3; // 60%, 80%, 100%
52
-
53
- for (int h = 0; h < numHues; h++) {
54
- for (int s = 0; s < numSaturations; s++) {
55
- for (int v = 0; v < numValues; v++) {
56
- float hue = (h * 360.0f / numHues);
57
- float saturation = 0.6f + s * 0.2f;
58
- float value = 0.6f + v * 0.2f;
59
-
60
- // Convert HSV to BGR
61
- cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(hue / 360.0f, saturation, value));
62
- cv::Mat bgr;
63
- cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
64
-
65
- cv::Vec3f color = bgr.at<cv::Vec3f>(0, 0);
66
- candidates.push_back(color);
67
- }
68
- }
69
- }
47
+ // Candidate colors evenly distributed in HSV space (precomputed once)
48
+ const std::vector<cv::Vec3f>& candidates = CandidateColorPalette();
70
49
 
71
50
  // Find candidate with maximum minimum distance to existing colors
72
51
  float maxMinDistance = 0;
@@ -95,6 +74,14 @@ inline cv::Vec3f GenerateMaximallyDifferentColor(
95
74
  }
96
75
 
97
76
  /*------------------------------------------------------------------------*/
77
+ // Box as parsed from JS (normalized coordinates). Geometry that depends on
78
+ // the image size is resolved in Execute(), after the image is decoded.
79
+ struct ParsedBox {
80
+ std::vector<cv::Point2f> corners; // 4 normalized corners (TL, TR, BR, BL)
81
+ std::string className;
82
+ float confidence;
83
+ };
84
+
98
85
  class AddBBsWorker final : public Napi::AsyncWorker {
99
86
  public:
100
87
  AddBBsWorker(Napi::Function cb,
@@ -123,13 +110,16 @@ public:
123
110
  quality(quality),
124
111
  pngOptimize(pngOptimize)
125
112
  {
126
- const int64 t0 = cv::getTickCount();
127
-
128
- // Convert JavaScript image to OpenCV Mat
129
- imageMat = ConvertToMat(jsImg);
113
+ // JS thread: metadata + persistent reference only (no decode, no pixels)
114
+ try {
115
+ src_ = CaptureImage(jsImg);
116
+ } catch (const Napi::Error& e) {
117
+ captureFailed_ = true; SetError(e.Message());
118
+ } catch (const std::exception& e) {
119
+ captureFailed_ = true; SetError(e.what());
120
+ }
130
121
 
131
- // Parse class color map
132
- std::unordered_map<std::string, cv::Vec3f> userColorMap;
122
+ // Parse class color map (JS → plain map)
133
123
  Napi::Array colorMapKeys = classColorMap.GetPropertyNames();
134
124
  for (size_t i = 0; i < colorMapKeys.Length(); i++) {
135
125
  std::string className = colorMapKeys.Get(i).As<Napi::String>().Utf8Value();
@@ -140,15 +130,11 @@ public:
140
130
  float g = std::stoi(hexColor.substr(3, 2), nullptr, 16) / 255.0f;
141
131
  float b = std::stoi(hexColor.substr(5, 2), nullptr, 16) / 255.0f;
142
132
  userColorMap[className] = cv::Vec3f(b, g, r); // BGR for OpenCV
143
- // Debug: Print parsed color
144
- // printf("Class %s: hex=%s -> BGR=(%.2f,%.2f,%.2f)\n", className.c_str(), hexColor.c_str(), b, g, r);
145
133
  }
146
134
  }
147
135
 
148
- // Reserve capacity for better performance
149
- bboxInfos.reserve(32); // Reserve for typical number of boxes
150
-
151
- // Parse boxes array structure - direct array format
136
+ // Parse boxes array structure (JS → plain structs, normalized coords)
137
+ parsedBoxes.reserve(boxesArray.Length());
152
138
  for (size_t boxIndex = 0; boxIndex < boxesArray.Length(); boxIndex++) {
153
139
  Napi::Object boxObj = boxesArray.Get(boxIndex).As<Napi::Object>();
154
140
 
@@ -158,108 +144,113 @@ public:
158
144
  if (box.Length() != 4) continue;
159
145
 
160
146
  // Parse 4 corners: [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
161
- std::vector<cv::Point2f> corners;
147
+ ParsedBox pb;
148
+ pb.corners.reserve(4);
162
149
  for (size_t i = 0; i < 4; i++) {
163
150
  Napi::Array corner = box.Get(i).As<Napi::Array>();
164
151
  if (corner.Length() >= 2) {
165
152
  float x = corner.Get(0u).As<Napi::Number>().FloatValue();
166
153
  float y = corner.Get(1u).As<Napi::Number>().FloatValue();
167
- corners.emplace_back(x, y);
154
+ pb.corners.emplace_back(x, y);
168
155
  }
169
156
  }
170
-
171
- if (corners.size() != 4) continue;
157
+ if (pb.corners.size() != 4) continue;
172
158
 
173
159
  // Extract tag (class name) and confidence
174
- std::string className = boxObj.Get("tag").As<Napi::String>().Utf8Value();
175
- float confidence = boxObj.Has("confidence") ?
176
- boxObj.Get("confidence").As<Napi::Number>().FloatValue() : 1.0f;
177
-
178
- // Skip unmapped classes if onlyMapped is true
179
- if (onlyMapped) {
180
- if (userColorMap.find(className) == userColorMap.end()) {
181
- continue; // Skip this box
182
- }
183
- }
184
-
185
- // Get color for this class and pre-compute BGR scalar
186
- cv::Vec3f color;
187
- auto colorIt = userColorMap.find(className);
188
- if (colorIt != userColorMap.end()) {
189
- color = colorIt->second;
190
- } else {
191
- color = GenerateMaximallyDifferentColor(className, userColorMap, colorCache);
192
- }
160
+ pb.className = boxObj.Get("tag").As<Napi::String>().Utf8Value();
161
+ pb.confidence = boxObj.Has("confidence") ?
162
+ boxObj.Get("confidence").As<Napi::Number>().FloatValue() : 1.0f;
193
163
 
194
- // Pre-compute BGR color as Scalar for faster drawing
195
- cv::Scalar bgrColor(
196
- color[0] * 255.0f, // B
197
- color[1] * 255.0f, // G
198
- color[2] * 255.0f // R
199
- );
200
-
201
- // Convert normalized corners to pixel coordinates
202
- std::vector<cv::Point> pixelCorners;
203
- pixelCorners.reserve(4);
204
- float minX = corners[0].x, maxX = corners[0].x;
205
- float minY = corners[0].y, maxY = corners[0].y;
206
- for (int i = 0; i < 4; i++) {
207
- int px = static_cast<int>(corners[i].x * imageMat.cols);
208
- int py = static_cast<int>(corners[i].y * imageMat.rows);
209
- px = std::max(0, std::min(imageMat.cols - 1, px));
210
- py = std::max(0, std::min(imageMat.rows - 1, py));
211
- pixelCorners.emplace_back(px, py);
212
- minX = std::min(minX, corners[i].x);
213
- maxX = std::max(maxX, corners[i].x);
214
- minY = std::min(minY, corners[i].y);
215
- maxY = std::max(maxY, corners[i].y);
216
- }
217
-
218
- // Axis-aligned bounding rect (for label positioning)
219
- cv::Rect bbox;
220
- bbox.x = static_cast<int>(minX * imageMat.cols);
221
- bbox.y = static_cast<int>(minY * imageMat.rows);
222
- bbox.width = static_cast<int>((maxX - minX) * imageMat.cols);
223
- bbox.height = static_cast<int>((maxY - minY) * imageMat.rows);
224
- bbox.x = std::max(0, std::min(imageMat.cols - 1, bbox.x));
225
- bbox.y = std::max(0, std::min(imageMat.rows - 1, bbox.y));
226
- bbox.width = std::min(bbox.width, imageMat.cols - bbox.x);
227
- bbox.height = std::min(bbox.height, imageMat.rows - bbox.y);
228
-
229
- // Pre-generate label text with optimized string handling
230
- char labelBuffer[256];
231
- if (showClassName && showConfidence) {
232
- snprintf(labelBuffer, sizeof(labelBuffer), "%s (%.1f%%)", className.c_str(), confidence * 100.0f);
233
- } else if (showClassName) {
234
- snprintf(labelBuffer, sizeof(labelBuffer), "%s", className.c_str());
235
- } else if (showConfidence) {
236
- snprintf(labelBuffer, sizeof(labelBuffer), "%.1f%%", confidence * 100.0f);
237
- } else {
238
- labelBuffer[0] = '\0';
239
- }
240
- std::string labelText(labelBuffer);
241
-
242
- // Store bbox info with pre-computed values
243
- BBoxInfo info;
244
- info.boundingRect = bbox;
245
- info.cornersPx = pixelCorners;
246
- info.className = className;
247
- info.confidence = confidence;
248
- info.bgrColor = bgrColor;
249
- info.labelText = labelText;
250
- bboxInfos.push_back(info);
164
+ parsedBoxes.push_back(std::move(pb));
251
165
  }
252
166
  }
253
-
254
- imageFormat = DetectChannelFormatShared(jsImg, imageMat);
255
- outputChannel = imageFormat;
256
-
257
- convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
258
167
  }
259
168
 
260
169
  protected:
261
170
  void Execute() override {
262
- const int64 t0 = cv::getTickCount();
171
+ if (captureFailed_) return;
172
+
173
+ // Decode (encoded inputs only) on the worker thread
174
+ int64 t0 = cv::getTickCount();
175
+ src_.Materialize();
176
+ const cv::Mat& imageMat = src_.mat;
177
+ imageFormat = src_.colorSpace;
178
+ outputChannel = imageFormat;
179
+
180
+ // Resolve colors, labels and pixel geometry now that the image size is known
181
+ bboxInfos.clear();
182
+ bboxInfos.reserve(parsedBoxes.size());
183
+ for (const auto& pb : parsedBoxes) {
184
+ // Skip unmapped classes if onlyMapped is true
185
+ if (onlyMapped && userColorMap.find(pb.className) == userColorMap.end()) {
186
+ continue;
187
+ }
188
+
189
+ // Get color for this class and pre-compute BGR scalar
190
+ cv::Vec3f color;
191
+ auto colorIt = userColorMap.find(pb.className);
192
+ if (colorIt != userColorMap.end()) {
193
+ color = colorIt->second;
194
+ } else {
195
+ auto cachedIt = colorCache.find(pb.className);
196
+ color = (cachedIt != colorCache.end())
197
+ ? cachedIt->second
198
+ : GenerateMaximallyDifferentColor(pb.className, userColorMap, colorCache);
199
+ }
200
+ cv::Scalar bgrColor(color[0] * 255.0f, color[1] * 255.0f, color[2] * 255.0f);
201
+
202
+ // Convert normalized corners to pixel coordinates
203
+ std::vector<cv::Point> pixelCorners;
204
+ pixelCorners.reserve(4);
205
+ float minX = pb.corners[0].x, maxX = pb.corners[0].x;
206
+ float minY = pb.corners[0].y, maxY = pb.corners[0].y;
207
+ for (int i = 0; i < 4; i++) {
208
+ int px = static_cast<int>(pb.corners[i].x * imageMat.cols);
209
+ int py = static_cast<int>(pb.corners[i].y * imageMat.rows);
210
+ px = std::max(0, std::min(imageMat.cols - 1, px));
211
+ py = std::max(0, std::min(imageMat.rows - 1, py));
212
+ pixelCorners.emplace_back(px, py);
213
+ minX = std::min(minX, pb.corners[i].x);
214
+ maxX = std::max(maxX, pb.corners[i].x);
215
+ minY = std::min(minY, pb.corners[i].y);
216
+ maxY = std::max(maxY, pb.corners[i].y);
217
+ }
218
+
219
+ // Axis-aligned bounding rect (for label positioning)
220
+ cv::Rect bbox;
221
+ bbox.x = static_cast<int>(minX * imageMat.cols);
222
+ bbox.y = static_cast<int>(minY * imageMat.rows);
223
+ bbox.width = static_cast<int>((maxX - minX) * imageMat.cols);
224
+ bbox.height = static_cast<int>((maxY - minY) * imageMat.rows);
225
+ bbox.x = std::max(0, std::min(imageMat.cols - 1, bbox.x));
226
+ bbox.y = std::max(0, std::min(imageMat.rows - 1, bbox.y));
227
+ bbox.width = std::min(bbox.width, imageMat.cols - bbox.x);
228
+ bbox.height = std::min(bbox.height, imageMat.rows - bbox.y);
229
+
230
+ // Pre-generate label text with optimized string handling
231
+ char labelBuffer[256];
232
+ if (showClassName && showConfidence) {
233
+ snprintf(labelBuffer, sizeof(labelBuffer), "%s (%.1f%%)", pb.className.c_str(), pb.confidence * 100.0f);
234
+ } else if (showClassName) {
235
+ snprintf(labelBuffer, sizeof(labelBuffer), "%s", pb.className.c_str());
236
+ } else if (showConfidence) {
237
+ snprintf(labelBuffer, sizeof(labelBuffer), "%.1f%%", pb.confidence * 100.0f);
238
+ } else {
239
+ labelBuffer[0] = '\0';
240
+ }
241
+
242
+ BBoxInfo info;
243
+ info.boundingRect = bbox;
244
+ info.cornersPx = std::move(pixelCorners);
245
+ info.className = pb.className;
246
+ info.confidence = pb.confidence;
247
+ info.bgrColor = bgrColor;
248
+ info.labelText = labelBuffer;
249
+ bboxInfos.push_back(std::move(info));
250
+ }
251
+
252
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
253
+ t0 = cv::getTickCount();
263
254
 
264
255
  // Work directly on the image if possible, avoid clone
265
256
  bool needsConversion = (imageFormat == "RGB" || imageFormat == "RGBA" || imageFormat == "GRAY");
@@ -274,7 +265,7 @@ protected:
274
265
  cv::cvtColor(imageMat, result, cv::COLOR_GRAY2BGR);
275
266
  }
276
267
  } else {
277
- // Already BGR/BGRA - clone only if needed
268
+ // Already BGR/BGRA - clone (never draw into JS-owned memory)
278
269
  result = imageMat.clone();
279
270
  }
280
271
 
@@ -368,6 +359,7 @@ protected:
368
359
  cv::cvtColor(result, result, cv::COLOR_BGR2GRAY);
369
360
  }
370
361
  // If already BGR/BGRA, no conversion needed
362
+ FinalizeForOutput(result);
371
363
  } else {
372
364
  // For encoded formats, keep as BGR
373
365
  cv::Mat tmp = result;
@@ -387,10 +379,18 @@ protected:
387
379
  Callback().Call({env.Null(), out});
388
380
  }
389
381
 
382
+ void OnError(const Napi::Error& e) override {
383
+ Callback().Call({ e.Value(), Env().Null() });
384
+ }
385
+
390
386
  private:
391
- cv::Mat imageMat, result;
387
+ ImageSource src_;
388
+ bool captureFailed_ = false;
389
+ cv::Mat result;
392
390
  std::string imageFormat, outputChannel;
391
+ std::vector<ParsedBox> parsedBoxes;
393
392
  std::vector<BBoxInfo> bboxInfos;
393
+ std::unordered_map<std::string, cv::Vec3f> userColorMap;
394
394
  bool showClassName, showConfidence, onlyMapped, labelBackground;
395
395
  int boxThickness;
396
396
  double fontSize;
@@ -48,12 +48,15 @@ public:
48
48
  outputFormat(std::move(outputFormat)),
49
49
  quality(quality), pngOptimize(pngOptimize)
50
50
  {
51
- // Timing and conversion
52
- const int64 t0 = cv::getTickCount();
53
-
54
- // Convert JavaScript image to OpenCV Mat
55
- imageMat = ConvertToMat(jsImg);
56
-
51
+ // JS thread: metadata + persistent reference only (no decode, no pixels)
52
+ try {
53
+ src_ = CaptureImage(jsImg);
54
+ } catch (const Napi::Error& e) {
55
+ captureFailed_ = true; SetError(e.Message());
56
+ } catch (const std::exception& e) {
57
+ captureFailed_ = true; SetError(e.what());
58
+ }
59
+
57
60
  // Parse polygon coordinates from JavaScript array
58
61
  polygon.reserve(polygonArray.Length());
59
62
  for (size_t i = 0; i < polygonArray.Length(); i++) {
@@ -65,18 +68,22 @@ public:
65
68
  }
66
69
  }
67
70
 
68
- // Detect image channel format
69
- imageFormat = DetectChannelFormatShared(jsImg, imageMat);
70
-
71
- // For polygon-based masking, output format matches image format
72
- outputChannel = imageFormat;
73
-
74
- convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
75
71
  }
76
72
 
77
73
  protected:
78
74
  void Execute() override {
79
- const int64 t0 = cv::getTickCount();
75
+ if (captureFailed_) return;
76
+
77
+ // Decode (encoded inputs only) on the worker thread
78
+ int64 t0 = cv::getTickCount();
79
+ src_.Materialize();
80
+ const cv::Mat& imageMat = src_.mat;
81
+ imageFormat = src_.colorSpace;
82
+ // For polygon-based masking, output format matches image format
83
+ outputChannel = imageFormat;
84
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
85
+
86
+ t0 = cv::getTickCount();
80
87
 
81
88
  // Convert image to target format
82
89
  cv::Mat img = ConvertToTargetFormatShared(imageMat, imageFormat, outputChannel);
@@ -155,6 +162,8 @@ protected:
155
162
  if (outputFormat != "raw") {
156
163
  cv::Mat tmp = PrepareForEncoding(result, outputChannel, outputFormat);
157
164
  encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
165
+ } else {
166
+ FinalizeForOutput(result);
158
167
  }
159
168
  }
160
169
 
@@ -169,8 +178,14 @@ protected:
169
178
  Callback().Call({env.Null(), out});
170
179
  }
171
180
 
181
+ void OnError(const Napi::Error& e) override {
182
+ Callback().Call({ e.Value(), Env().Null() });
183
+ }
184
+
172
185
  private:
173
- cv::Mat imageMat, result;
186
+ ImageSource src_;
187
+ bool captureFailed_ = false;
188
+ cv::Mat result;
174
189
  std::string imageFormat, outputChannel;
175
190
  std::vector<cv::Point2f> polygon;
176
191
  double maskStrength;