@rosepetal/node-red-contrib-image-tools 1.6.4 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/.github/workflows/build-prebuild.yml +1 -1
  3. package/README.md +41 -21
  4. package/docs/index.md +156 -0
  5. package/docs/nodes/blend/add-bbs.md +116 -0
  6. package/docs/nodes/blend/add-mask.md +67 -224
  7. package/docs/nodes/blend/add-masks.md +74 -196
  8. package/docs/nodes/blend/blend.md +84 -200
  9. package/docs/nodes/io/folder-in.md +92 -0
  10. package/docs/nodes/io/image-in.md +61 -52
  11. package/docs/nodes/io/image-out.md +114 -93
  12. package/docs/nodes/mix/advanced-mosaic.md +124 -78
  13. package/docs/nodes/mix/concat.md +71 -56
  14. package/docs/nodes/mix/mosaic.md +81 -91
  15. package/docs/nodes/specialized/cropBB.md +76 -214
  16. package/docs/nodes/specialized/heat-diff.md +111 -0
  17. package/docs/nodes/specialized/image-align.md +125 -387
  18. package/docs/nodes/transform/color-convert.md +101 -0
  19. package/docs/nodes/transform/crop.md +56 -58
  20. package/docs/nodes/transform/draw.md +46 -26
  21. package/docs/nodes/transform/filter.md +110 -46
  22. package/docs/nodes/transform/padding.md +55 -55
  23. package/docs/nodes/transform/resize.md +81 -56
  24. package/docs/nodes/transform/rotate.md +67 -50
  25. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  26. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  27. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  28. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  29. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  30. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  31. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  32. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  33. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +11 -4
  34. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +5 -4
  35. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  36. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  37. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  38. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  39. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  40. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  41. package/npm/darwin-arm64/package.json +1 -1
  42. package/npm/darwin-x64/package.json +1 -1
  43. package/npm/linux-arm64/package.json +1 -1
  44. package/npm/linux-x64/package.json +1 -1
  45. package/npm/linuxmusl-x64/package.json +1 -1
  46. package/npm/win32-x64/package.json +1 -1
  47. package/package.json +6 -6
  48. package/rosepetal-image-engine/binding.gyp +2 -1
  49. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  50. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  51. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  52. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  53. package/rosepetal-image-engine/src/blend.cpp +34 -20
  54. package/rosepetal-image-engine/src/codec.cpp +157 -0
  55. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  56. package/rosepetal-image-engine/src/concat.cpp +38 -43
  57. package/rosepetal-image-engine/src/crop.cpp +23 -26
  58. package/rosepetal-image-engine/src/draw.cpp +33 -10
  59. package/rosepetal-image-engine/src/filter.cpp +22 -26
  60. package/rosepetal-image-engine/src/heat-diff.cpp +35 -8
  61. package/rosepetal-image-engine/src/image-align.cpp +107 -35
  62. package/rosepetal-image-engine/src/main.cpp +4 -0
  63. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  64. package/rosepetal-image-engine/src/padding.cpp +30 -29
  65. package/rosepetal-image-engine/src/resize.cpp +20 -25
  66. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  67. package/rosepetal-image-engine/src/utils.h +243 -144
  68. package/scripts/build-opencv-static.sh +6 -0
  69. package/scripts/dual-register.js +32 -25
  70. package/scripts/sync-version.js +58 -41
@@ -22,34 +22,28 @@ public:
22
22
  quality(quality),
23
23
  pngOptimize(pngOptimize)
24
24
  {
25
+ // JS thread: metadata + persistent reference only (no decode, no pixels)
25
26
  try {
26
- inputMat = ConvertToMat(imgVal); // zero-copy RAW
27
-
28
- if (imgVal.IsObject() && !imgVal.IsBuffer()) {
29
- Napi::Object obj = imgVal.As<Napi::Object>();
30
-
31
- // Check for new colorSpace field first
32
- if (obj.Has("colorSpace")) {
33
- channelOrder = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
34
- }
35
- // Default based on channel count
36
- else {
37
- channelOrder = (inputMat.channels() == 4) ? "RGBA"
38
- : (inputMat.channels() == 3) ? "RGB"
39
- : "GRAY";
40
- }
41
- } else {
42
- // Buffer input - determine from OpenCV Mat
43
- channelOrder = (inputMat.channels() == 4) ? "RGBA"
44
- : (inputMat.channels() == 3) ? "RGB"
45
- : "GRAY";
46
- }
47
- } catch (const Napi::Error& e) { SetError(e.Message()); }
27
+ src_ = CaptureImage(imgVal);
28
+ } catch (const Napi::Error& e) {
29
+ captureFailed_ = true; SetError(e.Message());
30
+ } catch (const std::exception& e) {
31
+ captureFailed_ = true; SetError(e.what());
32
+ }
48
33
  }
49
34
 
50
35
  protected:
51
36
  void Execute() override {
37
+ if (captureFailed_) return;
52
38
  try {
39
+ // Decode (encoded inputs only) on the worker thread
40
+ auto tc = std::chrono::steady_clock::now();
41
+ src_.Materialize();
42
+ inputMat = src_.mat;
43
+ channelOrder = src_.colorSpace;
44
+ convertMs = std::chrono::duration<double,std::milli>(
45
+ std::chrono::steady_clock::now() - tc).count();
46
+
53
47
  auto t0 = std::chrono::steady_clock::now();
54
48
 
55
49
  // Ajustar color al orden real de la imagen
@@ -91,6 +85,8 @@ protected:
91
85
  const cv::Mat srcForEncoding =
92
86
  PrepareForEncoding(resultMat, channelOrder, outputFormat);
93
87
  encodeMs = EncodeToFormat(srcForEncoding, encodedBuf, outputFormat, quality, pngOptimize);
88
+ } else {
89
+ FinalizeForOutput(resultMat); // alias of JS memory → owned copy (worker thread)
94
90
  }
95
91
  } catch (const std::exception& e) { SetError(e.what()); }
96
92
  }
@@ -103,7 +99,7 @@ protected:
103
99
 
104
100
  Napi::Object res = Napi::Object::New(env);
105
101
  res.Set("image", jsImg);
106
- res.Set("timing", MakeTimingJS(env, 0.0, taskMs, encodeMs)); // convertMs=0
102
+ res.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
107
103
  Callback().Call({ env.Null(), res });
108
104
  }
109
105
 
@@ -112,14 +108,17 @@ protected:
112
108
  }
113
109
 
114
110
  private:
111
+ ImageSource src_;
115
112
  cv::Mat inputMat, resultMat;
116
113
  double angleDeg;
117
114
  cv::Scalar padColorRGB, padClrImg;
118
115
  std::string outputFormat;
119
116
  int quality;
120
117
  bool pngOptimize;
118
+ bool captureFailed_ = false;
121
119
 
122
120
  std::string channelOrder;
121
+ double convertMs = 0.0;
123
122
  double taskMs = 0.0;
124
123
  double encodeMs = 0.0;
125
124
  std::vector<uchar> encodedBuf;
@@ -8,117 +8,208 @@
8
8
  #include <vector>
9
9
  #include <string>
10
10
  #include <chrono>
11
+ #include <stdexcept>
11
12
 
12
13
  /**
13
- * Converts JS input to cv::Mat supporting:
14
- * - Image object: {data, width, height, channels, colorSpace, dtype}
15
- * - Buffer: Raw image file data (JPEG/PNG/WebP)
14
+ * ImageSource — a JS image input captured on the JS thread, decoded on the
15
+ * worker thread.
16
+ *
17
+ * Supported inputs:
18
+ * - Raw image object {data, width, height, channels, colorSpace, dtype}:
19
+ * the cv::Mat is a zero-copy view over the JS Buffer. `mat` and
20
+ * `colorSpace` are valid immediately after CaptureImage().
21
+ * - Encoded Buffer (JPEG/PNG/WebP/BMP...): only the pointer/length are
22
+ * captured. Nothing is decoded until Materialize() is called, which MUST
23
+ * happen inside AsyncWorker::Execute() so cv::imdecode never blocks the
24
+ * Node.js event loop.
25
+ *
26
+ * A persistent reference to the JS Buffer keeps its memory alive for the
27
+ * whole lifetime of the worker (the reference is released on the JS thread
28
+ * when the worker is destroyed).
16
29
  */
17
- inline cv::Mat ConvertToMat(const Napi::Value& input) {
30
+ struct ImageSource {
31
+ cv::Mat mat; // raw: zero-copy view; encoded: filled by Materialize()
32
+ std::string colorSpace; // "GRAY" | "RGB" | "RGBA" | "BGR" | "BGRA"
33
+ bool encoded = false;
34
+ const uchar* encPtr = nullptr;
35
+ size_t encLen = 0;
36
+ Napi::ObjectReference ref; // keeps the JS Buffer alive (move-only)
37
+
38
+ ImageSource() = default;
39
+ ImageSource(ImageSource&&) = default;
40
+ ImageSource& operator=(ImageSource&&) = default;
41
+ ImageSource(const ImageSource&) = delete;
42
+ ImageSource& operator=(const ImageSource&) = delete;
43
+
44
+ bool IsEncoded() const { return encoded; }
45
+ bool Ready() const { return !mat.empty(); }
46
+
47
+ // Worker-thread only. Decodes an encoded buffer (no-op for raw inputs).
48
+ // Throws std::runtime_error if the buffer cannot be decoded.
49
+ void Materialize() {
50
+ if (!encoded || !mat.empty()) return;
51
+ if (encPtr == nullptr || encLen == 0) {
52
+ throw std::runtime_error("Failed to decode image buffer: empty buffer.");
53
+ }
54
+ cv::Mat tmp(1, static_cast<int>(encLen), CV_8UC1, const_cast<uchar*>(encPtr));
55
+ cv::Mat img = cv::imdecode(tmp, cv::IMREAD_UNCHANGED);
56
+ if (img.empty()) {
57
+ throw std::runtime_error("Failed to decode image buffer.");
58
+ }
59
+ // imdecode returns BGR/BGRA regardless of file format; the toolkit
60
+ // labels decoded buffers as RGB/RGBA so we swap once here.
61
+ if (img.channels() == 3) cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
62
+ else if (img.channels() == 4) cv::cvtColor(img, img, cv::COLOR_BGRA2RGBA);
63
+ mat = img;
64
+ colorSpace = (img.channels() == 4) ? "RGBA" : (img.channels() == 3) ? "RGB" : "GRAY";
65
+ }
66
+ };
67
+
68
+ // Resolves the pointer/length of a Buffer / TypedArray / ArrayBuffer value.
69
+ inline bool ResolveBytes(const Napi::Value& v, const uchar*& ptr, size_t& len) {
70
+ if (v.IsBuffer()) {
71
+ auto b = v.As<Napi::Buffer<uint8_t>>();
72
+ ptr = b.Data(); len = b.Length();
73
+ return true;
74
+ }
75
+ if (v.IsTypedArray()) {
76
+ auto ta = v.As<Napi::TypedArray>();
77
+ auto ab = ta.ArrayBuffer();
78
+ ptr = static_cast<const uchar*>(ab.Data()) + ta.ByteOffset();
79
+ len = ta.ByteLength();
80
+ return true;
81
+ }
82
+ if (v.IsArrayBuffer()) {
83
+ auto ab = v.As<Napi::ArrayBuffer>();
84
+ ptr = static_cast<const uchar*>(ab.Data()); len = ab.ByteLength();
85
+ return true;
86
+ }
87
+ return false;
88
+ }
89
+
90
+ /**
91
+ * Captures a JS image input on the JS thread. Performs NO decoding and NO
92
+ * pixel work — only reads metadata and takes a persistent reference.
93
+ * Throws Napi::Error on invalid input.
94
+ */
95
+ inline ImageSource CaptureImage(const Napi::Value& input) {
18
96
  Napi::Env env = input.Env();
97
+ ImageSource src;
19
98
 
20
99
  // --- 1. Raw image object -------------------------
21
- if (input.IsObject() && !input.IsBuffer()) {
100
+ if (input.IsObject() && !input.IsBuffer() && !input.IsTypedArray() && !input.IsArrayBuffer()) {
22
101
  Napi::Object obj = input.As<Napi::Object>();
23
102
  if (obj.Has("data") && obj.Has("width") && obj.Has("height")) {
103
+ Napi::Value dataVal = obj.Get("data");
104
+ const uchar* ptr = nullptr; size_t len = 0;
105
+ if (!ResolveBytes(dataVal, ptr, len)) {
106
+ throw Napi::Error::New(env, "Image data must be a Buffer or TypedArray");
107
+ }
24
108
 
25
- auto dataBuf = obj.Get("data").As<Napi::Buffer<uint8_t>>();
26
-
27
109
  int width = obj.Get("width").As<Napi::Number>().Int32Value();
28
110
  int height = obj.Get("height").As<Napi::Number>().Int32Value();
111
+ if (width <= 0 || height <= 0) {
112
+ throw Napi::Error::New(env, "Invalid image dimensions");
113
+ }
29
114
 
30
115
  // Determine channel count and color space
31
116
  int channels = 3; // default
32
- std::string colorSpace = "RGB"; // default
33
-
117
+ std::string colorSpace;
118
+
34
119
  if (obj.Has("channels")) {
35
120
  auto channelsVal = obj.Get("channels");
36
-
37
121
  if (channelsVal.IsNumber()) {
38
122
  channels = channelsVal.As<Napi::Number>().Int32Value();
39
-
40
- // Get colorSpace if available
41
- if (obj.Has("colorSpace")) {
42
- colorSpace = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
43
- } else {
44
- // Default colorSpace based on channels
45
- switch (channels) {
46
- case 1: colorSpace = "GRAY"; break;
47
- case 3: colorSpace = "RGB"; break;
48
- case 4: colorSpace = "RGBA"; break;
49
- default:
50
- throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
51
- }
52
- }
53
123
  } else {
54
124
  throw Napi::Error::New(env, "Channels must be a number");
55
125
  }
56
126
  }
127
+ if (obj.Has("colorSpace") && obj.Get("colorSpace").IsString()) {
128
+ colorSpace = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
129
+ } else {
130
+ switch (channels) {
131
+ case 1: colorSpace = "GRAY"; break;
132
+ case 3: colorSpace = "RGB"; break;
133
+ case 4: colorSpace = "RGBA"; break;
134
+ default:
135
+ throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
136
+ }
137
+ }
57
138
 
58
139
  // Determine OpenCV type based on dtype and channels
59
140
  int cvType = CV_8UC3; // default
60
-
61
- if (obj.Has("dtype")) {
62
- std::string dtype = obj.Get("dtype").As<Napi::String>().Utf8Value();
63
- if (dtype == "uint8") {
64
- switch (channels) {
65
- case 1: cvType = CV_8UC1; break;
66
- case 3: cvType = CV_8UC3; break;
67
- case 4: cvType = CV_8UC4; break;
68
- default: throw Napi::Error::New(env, "Unsupported channel count for uint8: " + std::to_string(channels));
69
- }
70
- } else if (dtype == "uint16") {
71
- switch (channels) {
72
- case 1: cvType = CV_16UC1; break;
73
- case 3: cvType = CV_16UC3; break;
74
- case 4: cvType = CV_16UC4; break;
75
- default: throw Napi::Error::New(env, "Unsupported channel count for uint16: " + std::to_string(channels));
76
- }
77
- } else if (dtype == "float32") {
78
- switch (channels) {
79
- case 1: cvType = CV_32FC1; break;
80
- case 3: cvType = CV_32FC3; break;
81
- case 4: cvType = CV_32FC4; break;
82
- default: throw Napi::Error::New(env, "Unsupported channel count for float32: " + std::to_string(channels));
83
- }
84
- } else {
85
- throw Napi::Error::New(env, "Unsupported dtype: " + dtype);
86
- }
87
- } else {
88
- // Default uint8 handling
141
+ size_t elemBytes = 1;
142
+ std::string dtype = "uint8";
143
+ if (obj.Has("dtype") && obj.Get("dtype").IsString()) {
144
+ dtype = obj.Get("dtype").As<Napi::String>().Utf8Value();
145
+ }
146
+ if (dtype == "uint8") {
147
+ elemBytes = 1;
89
148
  switch (channels) {
90
149
  case 1: cvType = CV_8UC1; break;
91
150
  case 3: cvType = CV_8UC3; break;
92
151
  case 4: cvType = CV_8UC4; break;
93
- default: throw Napi::Error::New(env, "Unsupported channel count: " + std::to_string(channels));
152
+ default: throw Napi::Error::New(env, "Unsupported channel count for uint8: " + std::to_string(channels));
153
+ }
154
+ } else if (dtype == "uint16") {
155
+ elemBytes = 2;
156
+ switch (channels) {
157
+ case 1: cvType = CV_16UC1; break;
158
+ case 3: cvType = CV_16UC3; break;
159
+ case 4: cvType = CV_16UC4; break;
160
+ default: throw Napi::Error::New(env, "Unsupported channel count for uint16: " + std::to_string(channels));
94
161
  }
162
+ } else if (dtype == "float32") {
163
+ elemBytes = 4;
164
+ switch (channels) {
165
+ case 1: cvType = CV_32FC1; break;
166
+ case 3: cvType = CV_32FC3; break;
167
+ case 4: cvType = CV_32FC4; break;
168
+ default: throw Napi::Error::New(env, "Unsupported channel count for float32: " + std::to_string(channels));
169
+ }
170
+ } else {
171
+ throw Napi::Error::New(env, "Unsupported dtype: " + dtype);
172
+ }
173
+
174
+ const size_t expected = static_cast<size_t>(width) * static_cast<size_t>(height) *
175
+ static_cast<size_t>(channels) * elemBytes;
176
+ if (len < expected) {
177
+ throw Napi::Error::New(env,
178
+ "Image data too small: expected " + std::to_string(expected) +
179
+ " bytes, got " + std::to_string(len));
95
180
  }
96
181
 
97
- return cv::Mat(height, width, cvType, dataBuf.Data());
182
+ src.mat = cv::Mat(height, width, cvType, const_cast<uchar*>(ptr));
183
+ src.colorSpace = colorSpace;
184
+ src.ref = Napi::Persistent(dataVal.As<Napi::Object>());
185
+ return src;
98
186
  }
99
187
  }
100
188
 
101
- // --- 2. Direct Buffer (JPEG/PNG/WebP file data) -------------------------
102
- if (input.IsBuffer()) {
103
- auto buf = input.As<Napi::Buffer<uint8_t>>();
104
- cv::Mat tmp(1, buf.Length(), CV_8UC1, buf.Data());
105
- cv::Mat img = cv::imdecode(tmp, cv::IMREAD_UNCHANGED);
106
-
107
- if (img.empty()) {
108
- throw Napi::Error::New(env, "Failed to decode image buffer.");
189
+ // --- 2. Encoded bytes (JPEG/PNG/WebP/BMP file data) -------------------------
190
+ {
191
+ const uchar* ptr = nullptr; size_t len = 0;
192
+ if (ResolveBytes(input, ptr, len)) {
193
+ src.encoded = true;
194
+ src.encPtr = ptr;
195
+ src.encLen = len;
196
+ src.ref = Napi::Persistent(input.As<Napi::Object>());
197
+ return src;
109
198
  }
110
-
111
- // imdecode returns BGR/BGRA regardless of file format, assume input is RGB/RGBA
112
- if (img.channels() == 3) cv::cvtColor(img, img, cv::COLOR_BGR2RGB);
113
- else if (img.channels() == 4) cv::cvtColor(img, img, cv::COLOR_BGRA2RGBA);
114
- return img; // RGB/RGBA/GRAY, matching the colorSpace labels nodes assign
115
199
  }
116
200
 
117
201
  throw Napi::Error::New(env,
118
202
  "Invalid input: Expected Buffer or image object with {data, width, height}.");
119
203
  }
120
204
 
121
-
205
+ // Worker-thread helper: makes sure a result Mat owns contiguous memory so
206
+ // MatToRawJS() can hand it to JS with zero copies on the JS thread.
207
+ inline void FinalizeForOutput(cv::Mat& m) {
208
+ if (m.empty()) return;
209
+ if (!m.isContinuous() || m.u == nullptr) {
210
+ m = m.clone();
211
+ }
212
+ }
122
213
 
123
214
  // Convierte a BGR 3-canales para JPEG si hace falta
124
215
  inline cv::Mat ToBgrForJpg(const cv::Mat& src, const std::string& order) {
@@ -137,7 +228,8 @@ enum class ImageFormat {
137
228
  RAW = 0,
138
229
  JPG = 1,
139
230
  PNG = 2,
140
- WEBP = 3
231
+ WEBP = 3,
232
+ BMP = 4
141
233
  };
142
234
 
143
235
  // Convert format string to enum
@@ -145,12 +237,13 @@ inline ImageFormat ParseImageFormat(const std::string& format) {
145
237
  if (format == "jpg" || format == "jpeg") return ImageFormat::JPG;
146
238
  if (format == "png") return ImageFormat::PNG;
147
239
  if (format == "webp") return ImageFormat::WEBP;
240
+ if (format == "bmp") return ImageFormat::BMP;
148
241
  return ImageFormat::RAW;
149
242
  }
150
243
 
151
244
  // Convert to the correct channel order for OpenCV's encoders.
152
245
  // - JPG: requires BGR (alpha is dropped)
153
- // - PNG/WebP: support BGR/BGRA (alpha preserved for *A variants)
246
+ // - PNG/WebP/BMP: support BGR/BGRA (alpha preserved for *A variants)
154
247
  inline cv::Mat PrepareForEncoding(const cv::Mat& src,
155
248
  const std::string& order,
156
249
  const std::string& outputFormat)
@@ -160,7 +253,7 @@ inline cv::Mat PrepareForEncoding(const cv::Mat& src,
160
253
  return ToBgrForJpg(src, order);
161
254
  }
162
255
 
163
- // PNG/WebP: keep alpha when present
256
+ // PNG/WebP/BMP: keep alpha when present
164
257
  if (src.channels() == 1 || order == "BGR" || order == "BGRA" || order == "GRAY") {
165
258
  return src;
166
259
  }
@@ -234,6 +327,12 @@ inline double EncodeToFormat(const cv::Mat& src,
234
327
  cv::imencode(".webp", src, out, params);
235
328
  break;
236
329
  }
330
+ case ImageFormat::BMP: {
331
+ // Uncompressed BI_RGB; 8-bit gray (palette), 24-bit BGR or 32-bit BGRA.
332
+ out.reserve(src.total() * src.elemSize() + 1078);
333
+ cv::imencode(".bmp", src, out);
334
+ break;
335
+ }
237
336
  default:
238
337
  // RAW format - should not reach here, handled at higher level
239
338
  throw std::runtime_error("RAW format encoding not supported");
@@ -333,27 +432,6 @@ t.Set("encodeMs", Napi::Number::New(env, encodeMs));
333
432
  return t;
334
433
  }
335
434
 
336
- // Helper function to detect channel format for individual images (shared between blend and concat)
337
- inline std::string DetectChannelFormatShared(const Napi::Value& jsImg, const cv::Mat& mat) {
338
- if (jsImg.IsObject() && !jsImg.IsBuffer()) {
339
- Napi::Object obj = jsImg.As<Napi::Object>();
340
-
341
- // Check for colorSpace field first
342
- if (obj.Has("colorSpace")) {
343
- return obj.Get("colorSpace").As<Napi::String>().Utf8Value();
344
- }
345
- // Default based on channel count
346
- else {
347
- const int channels = mat.channels();
348
- return (channels == 4) ? "RGBA" : (channels == 3) ? "RGB" : "GRAY";
349
- }
350
- } else {
351
- // Buffer input - determine from OpenCV Mat
352
- const int channels = mat.channels();
353
- return (channels == 4) ? "RGBA" : (channels == 3) ? "RGB" : "GRAY";
354
- }
355
- }
356
-
357
435
  // Helper function to convert image to target channel format (shared between blend and concat)
358
436
  inline cv::Mat ConvertToTargetFormatShared(const cv::Mat& src, const std::string& srcFormat, const std::string& targetFormat) {
359
437
  if (srcFormat == targetFormat) {
@@ -443,32 +521,31 @@ inline cv::Mat removeColorBackground(const cv::Mat& src, const cv::Scalar& bgCol
443
521
  cv::cvtColor(bg_mat, hsv_bg, cv::COLOR_BGR2HSV);
444
522
  cv::Vec3b target_hsv = hsv_bg.at<cv::Vec3b>(0, 0);
445
523
 
446
- // Create mask based on color distance in HSV space
447
- cv::Mat mask = cv::Mat::zeros(hsv_src.size(), CV_8UC1);
448
-
449
524
  // Calculate tolerance thresholds
450
525
  double h_tolerance = tolerance * 180; // Hue range: 0-180
451
526
  double s_tolerance = tolerance * 255; // Saturation range: 0-255
452
527
  double v_tolerance = tolerance * 255; // Value range: 0-255
453
-
454
- for (int y = 0; y < hsv_src.rows; y++) {
455
- for (int x = 0; x < hsv_src.cols; x++) {
456
- cv::Vec3b pixel_hsv = hsv_src.at<cv::Vec3b>(y, x);
457
-
458
- // Calculate distance in HSV space
459
- double h_diff = std::abs(pixel_hsv[0] - target_hsv[0]);
460
- double s_diff = std::abs(pixel_hsv[1] - target_hsv[1]);
461
- double v_diff = std::abs(pixel_hsv[2] - target_hsv[2]);
462
-
463
- // Handle hue wraparound (0 and 180 are close)
464
- if (h_diff > 90) h_diff = 180 - h_diff;
465
-
466
- // Check if pixel matches background color within tolerance
467
- if (h_diff <= h_tolerance && s_diff <= s_tolerance && v_diff <= v_tolerance) {
468
- mask.at<uchar>(y, x) = 255; // Mark for removal
469
- }
470
- }
471
- }
528
+
529
+ // Mask of pixels within tolerance of the background colour, computed with
530
+ // whole-image OpenCV operations (identical result to the former per-pixel
531
+ // loop: |h-t| with wraparound, |s-t|, |v-t|, all <= tolerance).
532
+ std::vector<cv::Mat> hsvCh;
533
+ cv::split(hsv_src, hsvCh);
534
+ cv::Mat hDiff, sDiff, vDiff;
535
+ cv::absdiff(hsvCh[0], cv::Scalar(target_hsv[0]), hDiff);
536
+ cv::absdiff(hsvCh[1], cv::Scalar(target_hsv[1]), sDiff);
537
+ cv::absdiff(hsvCh[2], cv::Scalar(target_hsv[2]), vDiff);
538
+ // Hue wraparound (0 and 180 are close): h = min(h, 180 - h)
539
+ cv::Mat hWrap;
540
+ cv::subtract(cv::Scalar(180), hDiff, hWrap);
541
+ cv::min(hDiff, hWrap, hDiff);
542
+
543
+ cv::Mat mh, ms, mv, mask;
544
+ cv::compare(hDiff, h_tolerance, mh, cv::CMP_LE);
545
+ cv::compare(sDiff, s_tolerance, ms, cv::CMP_LE);
546
+ cv::compare(vDiff, v_tolerance, mv, cv::CMP_LE);
547
+ cv::bitwise_and(mh, ms, mask);
548
+ cv::bitwise_and(mask, mv, mask); // 255 = mark for removal
472
549
 
473
550
  // Apply Gaussian blur to mask edges for smooth transitions
474
551
  if (tolerance > 0.01) {
@@ -551,41 +628,63 @@ inline cv::Mat alphaComposite(const cv::Mat& base, const cv::Mat& overlay, doubl
551
628
 
552
629
  result = cv::Mat::zeros(base_bgra.size(), CV_8UC4);
553
630
 
554
- // Perform alpha compositing pixel by pixel
555
- for (int y = 0; y < result.rows; y++) {
556
- for (int x = 0; x < result.cols; x++) {
557
- cv::Vec4b base_pixel = base_bgra.at<cv::Vec4b>(y, x);
558
- cv::Vec4b overlay_pixel = overlay_bgra.at<cv::Vec4b>(y, x);
559
-
560
- // Normalize alpha values [0, 1]
561
- double base_alpha = base_pixel[3] / 255.0;
562
- double overlay_alpha = (overlay_pixel[3] / 255.0) * overlayOpacity;
563
-
564
- // Alpha compositing formula: result = overlay * overlay_alpha + base * (1 - overlay_alpha)
565
- // But we need to handle the case where overlay is transparent
566
- double result_alpha = overlay_alpha + base_alpha * (1.0 - overlay_alpha);
567
-
568
- cv::Vec4b result_pixel;
569
-
570
- if (result_alpha > 0.001) { // Avoid division by very small numbers
571
- for (int c = 0; c < 3; c++) { // BGR channels
572
- double result_color = (overlay_pixel[c] * overlay_alpha +
573
- base_pixel[c] * base_alpha * (1.0 - overlay_alpha)) / result_alpha;
574
- result_pixel[c] = cv::saturate_cast<uchar>(result_color);
575
- }
576
- result_pixel[3] = cv::saturate_cast<uchar>(result_alpha * 255);
577
- } else {
578
- // Fully transparent
579
- result_pixel = cv::Vec4b(0, 0, 0, 0);
631
+ // Alpha compositing with row pointers (same arithmetic as the former
632
+ // per-pixel .at<>() loop). Fully transparent results stay at zero.
633
+ const int rows = result.rows, cols = result.cols;
634
+ cv::parallel_for_(cv::Range(0, rows), [&](const cv::Range& range) {
635
+ for (int y = range.start; y < range.end; y++) {
636
+ const uchar* b = base_bgra.ptr<uchar>(y);
637
+ const uchar* o = overlay_bgra.ptr<uchar>(y);
638
+ uchar* r = result.ptr<uchar>(y);
639
+ for (int x = 0; x < cols; x++, b += 4, o += 4, r += 4) {
640
+ // Normalize alpha values [0, 1]
641
+ const double base_alpha = b[3] / 255.0;
642
+ const double overlay_alpha = (o[3] / 255.0) * overlayOpacity;
643
+
644
+ // result = overlay * overlay_alpha + base * base_alpha * (1 - overlay_alpha)
645
+ const double result_alpha = overlay_alpha + base_alpha * (1.0 - overlay_alpha);
646
+ if (result_alpha <= 0.001) continue; // fully transparent → (0,0,0,0)
647
+
648
+ const double base_w = base_alpha * (1.0 - overlay_alpha);
649
+ r[0] = cv::saturate_cast<uchar>((o[0] * overlay_alpha + b[0] * base_w) / result_alpha);
650
+ r[1] = cv::saturate_cast<uchar>((o[1] * overlay_alpha + b[1] * base_w) / result_alpha);
651
+ r[2] = cv::saturate_cast<uchar>((o[2] * overlay_alpha + b[2] * base_w) / result_alpha);
652
+ r[3] = cv::saturate_cast<uchar>(result_alpha * 255);
580
653
  }
581
-
582
- result.at<cv::Vec4b>(y, x) = result_pixel;
583
654
  }
584
- }
655
+ });
585
656
 
586
657
  return result;
587
658
  }
588
659
 
660
+ // 216 candidate colours evenly spread over HSV (24 hues × 3 saturations × 3
661
+ // values), in BGR float [0,1]. Computed once per process instead of on every
662
+ // call (it used to cost 216 tiny cvtColor invocations per unmapped class).
663
+ inline const std::vector<cv::Vec3f>& CandidateColorPalette() {
664
+ static const std::vector<cv::Vec3f> palette = []() {
665
+ std::vector<cv::Vec3f> out;
666
+ const int numHues = 24; // Every 15 degrees
667
+ const int numSaturations = 3; // 60%, 80%, 100%
668
+ const int numValues = 3; // 60%, 80%, 100%
669
+ out.reserve(numHues * numSaturations * numValues);
670
+ for (int h = 0; h < numHues; h++) {
671
+ for (int s = 0; s < numSaturations; s++) {
672
+ for (int v = 0; v < numValues; v++) {
673
+ float hue = (h * 360.0f / numHues);
674
+ float saturation = 0.6f + s * 0.2f;
675
+ float value = 0.6f + v * 0.2f;
676
+ cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(hue / 360.0f, saturation, value));
677
+ cv::Mat bgr;
678
+ cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
679
+ out.push_back(bgr.at<cv::Vec3f>(0, 0));
680
+ }
681
+ }
682
+ }
683
+ return out;
684
+ }();
685
+ return palette;
686
+ }
687
+
589
688
  // Parse color string to cv::Scalar, supporting hex colors
590
689
  inline cv::Scalar parseColorString(const std::string& colorStr) {
591
690
  if (colorStr.empty()) {
@@ -41,9 +41,14 @@ echo "Configuring OpenCV..."
41
41
 
42
42
  # Detect platform for platform-specific flags
43
43
  PLATFORM_FLAGS=""
44
+ C_FLAGS=""
44
45
  if [[ "$OSTYPE" == "darwin"* ]]; then
45
46
  # macOS specific settings
46
47
  PLATFORM_FLAGS="-DCMAKE_OSX_DEPLOYMENT_TARGET=10.15"
48
+ # The Xcode 16 SDK defines TARGET_OS_MAC, which the bundled zlib 1.2.13 and libpng 1.6.37 read as
49
+ # classic Mac OS: zlib turns fdopen() into NULL (clashes with stdio.h) and libpng includes <fp.h>.
50
+ # Defining fdopen keeps zlib's macro out; math.h first sets the guard that skips <fp.h>.
51
+ C_FLAGS="-Dfdopen=fdopen -include math.h"
47
52
 
48
53
  # For Apple Silicon cross-compilation support
49
54
  if [[ "$(uname -m)" == "arm64" ]]; then
@@ -63,6 +68,7 @@ fi
63
68
 
64
69
  cmake .. \
65
70
  -DCMAKE_BUILD_TYPE=Release \
71
+ ${C_FLAGS:+"-DCMAKE_C_FLAGS=${C_FLAGS}"} \
66
72
  -DCMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \
67
73
  \
68
74
  -DBUILD_SHARED_LIBS=OFF \