@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
@@ -137,39 +137,34 @@ inline cv::Mat ConvertMaskArrayToMat(const Napi::Array& arr) {
137
137
  return BuildMaskFrom2DArray(arr);
138
138
  }
139
139
 
140
- inline cv::Mat ConvertMaskImageToMat(const Napi::Value& maskVal, const cv::Size& targetSize) {
141
- try {
142
- cv::Mat maskMat = ConvertToMat(maskVal);
143
- if (maskMat.empty()) return cv::Mat();
144
-
145
- cv::Mat singleChannel;
146
- if (maskMat.channels() == 4) {
147
- cv::extractChannel(maskMat, singleChannel, 3); // Prefer alpha channel
148
- } else if (maskMat.channels() == 3) {
149
- cv::cvtColor(maskMat, singleChannel, cv::COLOR_BGR2GRAY);
150
- } else {
151
- singleChannel = maskMat;
152
- }
153
-
154
- if (singleChannel.depth() != CV_8U) {
155
- cv::Mat tmp;
156
- singleChannel.convertTo(tmp, CV_8U, 255.0);
157
- singleChannel = tmp;
158
- }
140
+ // Worker-thread: turns a decoded mask image (1/3/4 channels) into a binary
141
+ // single-channel mask of the target size.
142
+ inline cv::Mat ConvertMaskMatToBinary(const cv::Mat& maskMat, const cv::Size& targetSize) {
143
+ if (maskMat.empty()) return cv::Mat();
144
+
145
+ cv::Mat singleChannel;
146
+ if (maskMat.channels() == 4) {
147
+ cv::extractChannel(maskMat, singleChannel, 3); // Prefer alpha channel
148
+ } else if (maskMat.channels() == 3) {
149
+ cv::cvtColor(maskMat, singleChannel, cv::COLOR_BGR2GRAY);
150
+ } else {
151
+ singleChannel = maskMat;
152
+ }
159
153
 
160
- cv::Mat binary;
161
- cv::threshold(singleChannel, binary, 0, 255, cv::THRESH_BINARY);
154
+ if (singleChannel.depth() != CV_8U) {
155
+ cv::Mat tmp;
156
+ singleChannel.convertTo(tmp, CV_8U, 255.0);
157
+ singleChannel = tmp;
158
+ }
162
159
 
163
- if (binary.size() != targetSize) {
164
- cv::resize(binary, binary, targetSize, 0, 0, cv::INTER_NEAREST);
165
- }
160
+ cv::Mat binary;
161
+ cv::threshold(singleChannel, binary, 0, 255, cv::THRESH_BINARY);
166
162
 
167
- return binary;
168
- } catch (const Napi::Error&) {
169
- return cv::Mat();
170
- } catch (...) {
171
- return cv::Mat();
163
+ if (binary.size() != targetSize) {
164
+ cv::resize(binary, binary, targetSize, 0, 0, cv::INTER_NEAREST);
172
165
  }
166
+
167
+ return binary;
173
168
  }
174
169
 
175
170
  inline cv::Mat NormalizeMaskBinary(cv::Mat mask, const cv::Size& targetSize) {
@@ -218,29 +213,8 @@ inline cv::Vec3f GenerateMaximallyDifferentColor(
218
213
  return firstColor;
219
214
  }
220
215
 
221
- // Generate candidate colors evenly distributed in HSV space
222
- std::vector<cv::Vec3f> candidates;
223
- const int numHues = 24; // Every 15 degrees
224
- const int numSaturations = 3; // 60%, 80%, 100%
225
- const int numValues = 3; // 60%, 80%, 100%
226
-
227
- for (int h = 0; h < numHues; h++) {
228
- for (int s = 0; s < numSaturations; s++) {
229
- for (int v = 0; v < numValues; v++) {
230
- float hue = (h * 360.0f / numHues);
231
- float saturation = 0.6f + s * 0.2f; // 60%, 80%, 100%
232
- float value = 0.6f + v * 0.2f; // 60%, 80%, 100%
233
-
234
- // Convert HSV to BGR
235
- cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(hue / 360.0f, saturation, value));
236
- cv::Mat bgr;
237
- cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
238
-
239
- cv::Vec3f color = bgr.at<cv::Vec3f>(0, 0);
240
- candidates.push_back(color);
241
- }
242
- }
243
- }
216
+ // Candidate colors evenly distributed in HSV space (precomputed once)
217
+ const std::vector<cv::Vec3f>& candidates = CandidateColorPalette();
244
218
 
245
219
  // Find candidate with maximum minimum distance to existing colors
246
220
  float maxMinDistance = 0;
@@ -284,6 +258,20 @@ inline cv::Vec3f GetCachedColor(const std::string& className) {
284
258
  }
285
259
 
286
260
  /*------------------------------------------------------------------------*/
261
+ // Mask entry as parsed from JS on the JS thread. Everything that touches
262
+ // pixels (rasterising polygons, decoding mask images, bounding boxes) is
263
+ // deferred to Execute().
264
+ struct PendingMask {
265
+ std::string className;
266
+ int originalIndex = 0;
267
+ int priority = 0;
268
+ cv::Vec3f color;
269
+ std::vector<std::vector<cv::Point2f>> polygons; // normalized coords
270
+ cv::Mat arrayMask; // built from a 2D JS array (JS-thread by nature)
271
+ ImageSource imageMask; // raw / encoded mask image, decoded in Execute()
272
+ bool hasImageMask = false;
273
+ };
274
+
287
275
  class AddMasksOptimizedWorker final : public Napi::AsyncWorker {
288
276
  public:
289
277
  AddMasksOptimizedWorker(Napi::Function cb,
@@ -302,10 +290,14 @@ public:
302
290
  outputFormat(std::move(outputFormat)),
303
291
  quality(quality), pngOptimize(pngOptimize)
304
292
  {
305
- const int64 t0 = cv::getTickCount();
306
-
307
- // Convert JavaScript image to OpenCV Mat
308
- imageMat = ConvertToMat(jsImg);
293
+ // JS thread: metadata + persistent reference only (no decode, no pixels)
294
+ try {
295
+ src_ = CaptureImage(jsImg);
296
+ } catch (const Napi::Error& e) {
297
+ captureFailed_ = true; SetError(e.Message());
298
+ } catch (const std::exception& e) {
299
+ captureFailed_ = true; SetError(e.what());
300
+ }
309
301
 
310
302
  // Build priority map from ordered array (lower index = higher priority)
311
303
  std::unordered_map<std::string, int> priorityMap;
@@ -331,6 +323,8 @@ public:
331
323
  }
332
324
  }
333
325
 
326
+ // Colour resolution stays on the JS thread: the process-wide colorCache
327
+ // is not thread-safe and the work is tiny (no image pixels involved).
334
328
  auto resolveColor = [&](const std::string& className) -> cv::Vec3f {
335
329
  auto colorIt = userColorMap.find(className);
336
330
  if (colorIt != userColorMap.end()) {
@@ -359,7 +353,8 @@ public:
359
353
  return INT_MAX / 2 + originalIndex;
360
354
  };
361
355
 
362
- // Pre-process all masks and create optimized structures
356
+ // Parse all masks (JS → plain structs). No rasterisation here.
357
+ pendingMasks.reserve(masksArray.Length());
363
358
  for (size_t maskIndex = 0; maskIndex < masksArray.Length(); maskIndex++) {
364
359
  if (!masksArray.Get(maskIndex).IsObject()) continue;
365
360
  Napi::Object maskObj = masksArray.Get(maskIndex).As<Napi::Object>();
@@ -367,8 +362,11 @@ public:
367
362
  std::string className = ExtractClassName(maskObj);
368
363
  if (className.empty()) continue;
369
364
 
370
- cv::Vec3f resolvedColor = resolveColor(className);
371
- bool addedPolygon = false;
365
+ PendingMask pm;
366
+ pm.className = className;
367
+ pm.originalIndex = static_cast<int>(maskIndex);
368
+ pm.priority = resolvePriority(className, static_cast<int>(maskIndex));
369
+ pm.color = resolveColor(className);
372
370
 
373
371
  // --- Polygons path (preferred when present) ---
374
372
  if (maskObj.Has("polygons") && maskObj.Get("polygons").IsArray()) {
@@ -380,7 +378,6 @@ public:
380
378
 
381
379
  Napi::Array coordinates = polygonsArray.Get(polyIdx).As<Napi::Array>();
382
380
 
383
- // Parse polygon coordinates
384
381
  std::vector<cv::Point2f> polygon;
385
382
  polygon.reserve(coordinates.Length());
386
383
 
@@ -397,50 +394,94 @@ public:
397
394
  }
398
395
 
399
396
  if (!polygon.empty()) {
400
- OptimizedMaskInfo maskInfo;
401
- maskInfo.className = className;
402
- maskInfo.normalizedColor = resolvedColor;
403
- maskInfo.priority = resolvePriority(className, static_cast<int>(maskIndex));
404
- maskInfo.originalIndex = static_cast<int>(maskIndex);
405
-
406
- // Create optimized mask with bounding box
407
- auto [mask, bbox] = CreateOptimizedPolygonMask(polygon, imageMat.size());
408
- maskInfo.binaryMask = mask;
409
- maskInfo.boundingBox = bbox;
410
-
411
- optimizedMasks.push_back(std::move(maskInfo));
412
- addedPolygon = true;
397
+ pm.polygons.push_back(std::move(polygon));
413
398
  }
414
399
  }
415
400
  }
416
401
 
417
402
  // --- Raw mask path (inferencer 'mask' output) ---
418
- if (!addedPolygon && maskObj.Has("mask")) {
419
- cv::Mat maskBinary;
403
+ if (pm.polygons.empty() && maskObj.Has("mask")) {
420
404
  Napi::Value maskVal = maskObj.Get("mask");
421
405
 
422
406
  if (maskVal.IsArray()) {
423
- maskBinary = ConvertMaskArrayToMat(maskVal.As<Napi::Array>());
407
+ // A 2D JS array can only be read on the JS thread
408
+ pm.arrayMask = ConvertMaskArrayToMat(maskVal.As<Napi::Array>());
424
409
  } else if (maskVal.IsBuffer() || maskVal.IsObject()) {
425
- maskBinary = ConvertMaskImageToMat(maskVal, imageMat.size());
410
+ try {
411
+ pm.imageMask = CaptureImage(maskVal);
412
+ pm.hasImageMask = true;
413
+ } catch (const Napi::Error&) {
414
+ // Invalid mask image: ignored (same behaviour as before)
415
+ } catch (const std::exception&) {
416
+ }
426
417
  }
418
+ }
427
419
 
428
- maskBinary = NormalizeMaskBinary(maskBinary, imageMat.size());
429
-
430
- if (!maskBinary.empty()) {
431
- std::vector<cv::Point> nonZeroPts;
432
- cv::findNonZero(maskBinary, nonZeroPts);
433
- if (!nonZeroPts.empty()) {
434
- cv::Rect bbox = cv::boundingRect(nonZeroPts);
435
- OptimizedMaskInfo maskInfo;
436
- maskInfo.className = className;
437
- maskInfo.normalizedColor = resolvedColor;
438
- maskInfo.priority = resolvePriority(className, static_cast<int>(maskIndex));
439
- maskInfo.originalIndex = static_cast<int>(maskIndex);
440
- maskInfo.boundingBox = bbox;
441
- maskInfo.binaryMask = maskBinary(bbox).clone();
442
- optimizedMasks.push_back(std::move(maskInfo));
443
- }
420
+ pendingMasks.push_back(std::move(pm));
421
+ }
422
+ }
423
+
424
+ protected:
425
+ void Execute() override {
426
+ if (captureFailed_) return;
427
+
428
+ // Decode (encoded inputs only) on the worker thread
429
+ int64 t0 = cv::getTickCount();
430
+ src_.Materialize();
431
+ const cv::Mat& imageMat = src_.mat;
432
+ imageFormat = src_.colorSpace;
433
+ outputChannel = imageFormat;
434
+
435
+ // Rasterise / decode / normalise all masks (worker thread)
436
+ optimizedMasks.clear();
437
+ for (auto& pm : pendingMasks) {
438
+ bool addedPolygon = false;
439
+
440
+ for (const auto& polygon : pm.polygons) {
441
+ OptimizedMaskInfo maskInfo;
442
+ maskInfo.className = pm.className;
443
+ maskInfo.normalizedColor = pm.color;
444
+ maskInfo.priority = pm.priority;
445
+ maskInfo.originalIndex = pm.originalIndex;
446
+
447
+ // Create optimized mask with bounding box
448
+ auto [mask, bbox] = CreateOptimizedPolygonMask(polygon, imageMat.size());
449
+ maskInfo.binaryMask = mask;
450
+ maskInfo.boundingBox = bbox;
451
+
452
+ optimizedMasks.push_back(std::move(maskInfo));
453
+ addedPolygon = true;
454
+ }
455
+
456
+ if (addedPolygon) continue;
457
+
458
+ cv::Mat maskBinary;
459
+ if (!pm.arrayMask.empty()) {
460
+ maskBinary = pm.arrayMask;
461
+ } else if (pm.hasImageMask) {
462
+ try {
463
+ pm.imageMask.Materialize();
464
+ maskBinary = ConvertMaskMatToBinary(pm.imageMask.mat, imageMat.size());
465
+ } catch (const std::exception&) {
466
+ maskBinary = cv::Mat(); // undecodable mask image: ignored
467
+ }
468
+ }
469
+
470
+ maskBinary = NormalizeMaskBinary(maskBinary, imageMat.size());
471
+
472
+ if (!maskBinary.empty()) {
473
+ std::vector<cv::Point> nonZeroPts;
474
+ cv::findNonZero(maskBinary, nonZeroPts);
475
+ if (!nonZeroPts.empty()) {
476
+ cv::Rect bbox = cv::boundingRect(nonZeroPts);
477
+ OptimizedMaskInfo maskInfo;
478
+ maskInfo.className = pm.className;
479
+ maskInfo.normalizedColor = pm.color;
480
+ maskInfo.priority = pm.priority;
481
+ maskInfo.originalIndex = pm.originalIndex;
482
+ maskInfo.boundingBox = bbox;
483
+ maskInfo.binaryMask = maskBinary(bbox).clone();
484
+ optimizedMasks.push_back(std::move(maskInfo));
444
485
  }
445
486
  }
446
487
  }
@@ -453,15 +494,8 @@ public:
453
494
  return a.originalIndex < b.originalIndex; // Tie-breaker: input order
454
495
  });
455
496
 
456
- imageFormat = DetectChannelFormatShared(jsImg, imageMat);
457
- outputChannel = imageFormat;
458
-
459
497
  convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
460
- }
461
-
462
- protected:
463
- void Execute() override {
464
- const int64 t0 = cv::getTickCount();
498
+ t0 = cv::getTickCount();
465
499
 
466
500
  // Convert image to target format
467
501
  cv::Mat img = ConvertToTargetFormatShared(imageMat, imageFormat, outputChannel);
@@ -562,6 +596,8 @@ protected:
562
596
  if (outputFormat != "raw") {
563
597
  cv::Mat tmp = PrepareForEncoding(result, outputChannel, outputFormat);
564
598
  encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
599
+ } else {
600
+ FinalizeForOutput(result);
565
601
  }
566
602
  }
567
603
 
@@ -576,9 +612,16 @@ protected:
576
612
  Callback().Call({env.Null(), out});
577
613
  }
578
614
 
615
+ void OnError(const Napi::Error& e) override {
616
+ Callback().Call({ e.Value(), Env().Null() });
617
+ }
618
+
579
619
  private:
580
- cv::Mat imageMat, result;
620
+ ImageSource src_;
621
+ bool captureFailed_ = false;
622
+ cv::Mat result;
581
623
  std::string imageFormat, outputChannel;
624
+ std::vector<PendingMask> pendingMasks;
582
625
  std::vector<OptimizedMaskInfo> optimizedMasks;
583
626
  float maskStrength;
584
627
  bool autoGenerateColors;