@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,740 @@
1
+ // ───────── src/advanced-mosaic.cpp ───────────────────────────────────────────────
2
+ // ADVANCED MOSAIC - Ultra-optimized image compositing with per-image transformations
3
+ // Combines resize, rotate, and positioning in a single high-performance pipeline
4
+ #include <napi.h>
5
+ #include <opencv2/opencv.hpp>
6
+ #include <vector>
7
+ #include <algorithm>
8
+ #include <cmath>
9
+ #include <string>
10
+ #include "utils.h"
11
+
12
+ // Lightweight helpers for mask handling (aligned with add-masks inputs)
13
+ static inline std::string ExtractClassNameAdvanced(const Napi::Object& obj) {
14
+ const std::vector<std::string> keys = {"tag", "class_name", "className", "label", "class"};
15
+ for (const auto& key : keys) {
16
+ if (obj.Has(key) && obj.Get(key).IsString()) {
17
+ std::string value = obj.Get(key).As<Napi::String>().Utf8Value();
18
+ if (!value.empty()) return value;
19
+ }
20
+ }
21
+ return "";
22
+ }
23
+
24
+ static inline cv::Mat BuildMaskFrom2DArray(const Napi::Array& rows) {
25
+ const uint32_t rowCount = rows.Length();
26
+ if (rowCount == 0) return cv::Mat();
27
+
28
+ int cols = -1;
29
+ for (uint32_t y = 0; y < rowCount; y++) {
30
+ if (rows.Get(y).IsArray()) {
31
+ cols = static_cast<int>(rows.Get(y).As<Napi::Array>().Length());
32
+ if (cols > 0) break;
33
+ }
34
+ }
35
+ if (cols <= 0) return cv::Mat();
36
+
37
+ cv::Mat mask(rowCount, cols, CV_8UC1, cv::Scalar(0));
38
+ for (uint32_t y = 0; y < rowCount; y++) {
39
+ if (!rows.Get(y).IsArray()) continue;
40
+ Napi::Array row = rows.Get(y).As<Napi::Array>();
41
+ const uint32_t rowLen = row.Length();
42
+ for (uint32_t x = 0; x < rowLen && x < static_cast<uint32_t>(cols); x++) {
43
+ if (row.Get(x).IsNumber()) {
44
+ double v = row.Get(x).As<Napi::Number>().DoubleValue();
45
+ if (std::isfinite(v) && v != 0.0) {
46
+ double scaled = v > 1.0 ? v : v * 255.0;
47
+ mask.at<uchar>(y, x) = static_cast<uchar>(std::clamp(scaled, 0.0, 255.0));
48
+ }
49
+ }
50
+ }
51
+ }
52
+ return mask;
53
+ }
54
+
55
+ static inline cv::Mat BuildMaskFromPolygons(const Napi::Array& polygons, const cv::Size& size) {
56
+ if (polygons.Length() == 0 || size.width <= 0 || size.height <= 0) return cv::Mat();
57
+ cv::Mat mask = cv::Mat::zeros(size, CV_8UC1);
58
+
59
+ for (uint32_t idx = 0; idx < polygons.Length(); idx++) {
60
+ if (!polygons.Get(idx).IsArray()) continue;
61
+ Napi::Array coords = polygons.Get(idx).As<Napi::Array>();
62
+ if (coords.Length() == 0) continue;
63
+
64
+ std::vector<cv::Point> points;
65
+ points.reserve(coords.Length());
66
+
67
+ for (uint32_t i = 0; i < coords.Length(); i++) {
68
+ if (!coords.Get(i).IsArray()) continue;
69
+ Napi::Array point = coords.Get(i).As<Napi::Array>();
70
+ if (point.Length() >= 2 && point.Get(0u).IsNumber() && point.Get(1u).IsNumber()) {
71
+ double x = point.Get(0u).As<Napi::Number>().DoubleValue();
72
+ double y = point.Get(1u).As<Napi::Number>().DoubleValue();
73
+ int px = static_cast<int>(std::round(x * size.width));
74
+ int py = static_cast<int>(std::round(y * size.height));
75
+ px = std::max(0, std::min(size.width - 1, px));
76
+ py = std::max(0, std::min(size.height - 1, py));
77
+ points.emplace_back(px, py);
78
+ }
79
+ }
80
+
81
+ if (points.size() >= 3) {
82
+ const cv::Point* pts = points.data();
83
+ int npts = static_cast<int>(points.size());
84
+ cv::fillPoly(mask, &pts, &npts, 1, cv::Scalar(255), cv::LINE_4);
85
+ }
86
+ }
87
+
88
+ return mask;
89
+ }
90
+
91
+ // Helper function to determine the best canvas format from multiple input formats
92
+ std::string DetermineBestCanvasFormatAdvanced(const std::vector<std::string>& channels) {
93
+ if (channels.empty()) return "BGR";
94
+
95
+ bool hasRGBA = false, hasBGRA = false, hasRGB = false, hasBGR = false;
96
+
97
+ for (const auto& ch : channels) {
98
+ if (ch == "RGBA") hasRGBA = true;
99
+ else if (ch == "BGRA") hasBGRA = true;
100
+ else if (ch == "RGB") hasRGB = true;
101
+ else if (ch == "BGR") hasBGR = true;
102
+ }
103
+
104
+ // Priority: RGBA > BGRA > RGB > BGR > GRAY
105
+ if (hasRGBA) return "RGBA";
106
+ if (hasBGRA) return "BGRA";
107
+ if (hasRGB) return "RGB";
108
+ if (hasBGR) return "BGR";
109
+ return "GRAY";
110
+ }
111
+
112
+ /*────────────────────────── ULTRA-FAST AdvancedMosaicWorker ───────────────────────────────────*/
113
+ class AdvancedMosaicWorker : public Napi::AsyncWorker {
114
+ public:
115
+ AdvancedMosaicWorker(Napi::Function cb,
116
+ const Napi::Array& imagesArray,
117
+ int canvasWidth, int canvasHeight,
118
+ const std::string& backgroundColor,
119
+ const Napi::Array& imageConfigsArray,
120
+ bool normalized, std::string outputFormat,
121
+ int quality,
122
+ bool pngOptimize,
123
+ bool hasMasks,
124
+ const Napi::Array& masksArray)
125
+ : Napi::AsyncWorker(cb),
126
+ canvasWidth_(canvasWidth), canvasHeight_(canvasHeight),
127
+ backgroundColor_(backgroundColor),
128
+ normalized_(normalized), outputFormat_(std::move(outputFormat)),
129
+ quality_(quality), pngOptimize_(pngOptimize),
130
+ hasMasks_(hasMasks)
131
+ {
132
+ /* ─ SUPER FAST image conversion with timing ─ */
133
+ const int64 t0 = cv::getTickCount();
134
+
135
+ // Pre-allocate vectors for maximum performance
136
+ images_.reserve(imagesArray.Length());
137
+ imageChannels_.reserve(imagesArray.Length());
138
+ imageConfigs_.reserve(imageConfigsArray.Length());
139
+
140
+ // Convert images with zero-copy operations and extract channel formats
141
+ for (uint32_t i = 0; i < imagesArray.Length(); i++) {
142
+ images_.emplace_back(ConvertToMat(imagesArray[i]));
143
+
144
+ // Extract and store channel format for each image
145
+ std::string channel;
146
+ if (imagesArray[i].IsObject() && !imagesArray[i].IsBuffer()) {
147
+ Napi::Object obj = imagesArray[i].As<Napi::Object>();
148
+
149
+ // Check for new colorSpace field first
150
+ if (obj.Has("colorSpace")) {
151
+ channel = obj.Get("colorSpace").As<Napi::String>().Utf8Value();
152
+ }
153
+ // Default based on channel count
154
+ else {
155
+ channel = (images_[i].channels() == 4) ? "BGRA"
156
+ : (images_[i].channels() == 3) ? "BGR"
157
+ : "GRAY";
158
+ }
159
+ } else {
160
+ // Buffer input - determine from OpenCV Mat
161
+ channel = (images_[i].channels() == 4) ? "BGRA"
162
+ : (images_[i].channels() == 3) ? "BGR"
163
+ : "GRAY";
164
+ }
165
+
166
+ imageChannels_.emplace_back(channel);
167
+ }
168
+
169
+ // Optional masks aligned with input images
170
+ if (hasMasks_) {
171
+ masks_.resize(images_.size());
172
+ maskTags_.resize(images_.size());
173
+ maskOutputs_.resize(images_.size());
174
+
175
+ for (uint32_t i = 0; i < masksArray.Length() && i < images_.size(); i++) {
176
+ Napi::Value mv = masksArray.Get(i);
177
+ cv::Mat maskMat;
178
+ std::string tag;
179
+
180
+ if (mv.IsObject() && !mv.IsArray()) {
181
+ Napi::Object mObj = mv.As<Napi::Object>();
182
+ tag = ExtractClassNameAdvanced(mObj);
183
+
184
+ if (mObj.Has("mask")) {
185
+ Napi::Value inner = mObj.Get("mask");
186
+ if (inner.IsArray()) {
187
+ maskMat = BuildMaskFrom2DArray(inner.As<Napi::Array>());
188
+ } else {
189
+ maskMat = ConvertToMat(inner);
190
+ }
191
+ } else if (mObj.Has("polygons") && mObj.Get("polygons").IsArray()) {
192
+ maskMat = BuildMaskFromPolygons(mObj.Get("polygons").As<Napi::Array>(), images_[i].size());
193
+ } else if (mObj.Has("data") && mObj.Has("width") && mObj.Has("height")) {
194
+ maskMat = ConvertToMat(mv);
195
+ }
196
+ } else if (mv.IsArray()) {
197
+ maskMat = BuildMaskFrom2DArray(mv.As<Napi::Array>());
198
+ } else if (mv.IsBuffer()) {
199
+ maskMat = ConvertToMat(mv);
200
+ }
201
+
202
+ if (!maskMat.empty()) {
203
+ if (maskMat.channels() > 1) {
204
+ cv::cvtColor(maskMat, maskMat, cv::COLOR_BGR2GRAY);
205
+ }
206
+ if (maskMat.depth() != CV_8U) {
207
+ cv::Mat tmp;
208
+ maskMat.convertTo(tmp, CV_8U, 255.0);
209
+ maskMat = tmp;
210
+ }
211
+ cv::threshold(maskMat, maskMat, 0, 255, cv::THRESH_BINARY);
212
+ masks_[i] = maskMat;
213
+ maskTags_[i] = tag;
214
+ maskOutputs_[i] = cv::Mat::zeros(canvasHeight_, canvasWidth_, CV_8UC1);
215
+ }
216
+ }
217
+ }
218
+
219
+ // Parse image configurations - ultra-fast operations
220
+ for (uint32_t i = 0; i < imageConfigsArray.Length(); i++) {
221
+ Napi::Object config = imageConfigsArray[i].As<Napi::Object>();
222
+ ImageConfig imgConfig;
223
+
224
+ imgConfig.arrayIndex = config.Get("arrayIndex").As<Napi::Number>().Int32Value();
225
+ imgConfig.x = config.Get("x").As<Napi::Number>().DoubleValue();
226
+ imgConfig.y = config.Get("y").As<Napi::Number>().DoubleValue();
227
+ imgConfig.rotation = config.Get("rotation").As<Napi::Number>().DoubleValue();
228
+ imgConfig.zIndex = config.Has("zIndex") ? config.Get("zIndex").As<Napi::Number>().Int32Value() : i;
229
+
230
+ // Handle optional width/height (null means keep original)
231
+ if (config.Has("width") && !config.Get("width").IsNull()) {
232
+ imgConfig.width = config.Get("width").As<Napi::Number>().Int32Value();
233
+ } else {
234
+ imgConfig.width = -1; // Keep original
235
+ }
236
+
237
+ if (config.Has("height") && !config.Get("height").IsNull()) {
238
+ imgConfig.height = config.Get("height").As<Napi::Number>().Int32Value();
239
+ } else {
240
+ imgConfig.height = -1; // Keep original
241
+ }
242
+
243
+ imageConfigs_.emplace_back(imgConfig);
244
+ }
245
+
246
+ // Sort by zIndex for proper layering
247
+ std::sort(imageConfigs_.begin(), imageConfigs_.end(),
248
+ [](const ImageConfig& a, const ImageConfig& b) {
249
+ return a.zIndex < b.zIndex;
250
+ });
251
+
252
+ // Check if any images have rotation to determine if we need alpha support
253
+ bool hasRotation = false;
254
+ for (const auto& config : imageConfigs_) {
255
+ if (std::abs(config.rotation) > 1e-3) {
256
+ hasRotation = true;
257
+ break;
258
+ }
259
+ }
260
+
261
+ // Determine the best canvas format, preferring RGBA if rotation is detected
262
+ if (hasRotation) {
263
+ canvasChannel_ = "RGBA"; // Force RGBA for transparent rotation padding
264
+ } else {
265
+ canvasChannel_ = DetermineBestCanvasFormatAdvanced(imageChannels_);
266
+ }
267
+
268
+ convertMs_ = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
269
+ }
270
+
271
+ protected:
272
+ void Execute() override {
273
+ /* ─ SUPER FAST advanced mosaic composition ─ */
274
+ const int64 t0 = cv::getTickCount();
275
+
276
+ // Parse background color - optimized hex parsing (returns BGR format)
277
+ cv::Scalar bgColor = ParseColor(backgroundColor_, cv::Scalar(0, 0, 0));
278
+
279
+ // Fix color inversion: ParseColor returns BGR, but we need to handle different canvas formats
280
+ if (canvasChannel_ == "RGB" || canvasChannel_ == "RGBA") {
281
+ // For RGB format canvas, swap B and R channels from BGR to RGB
282
+ std::swap(bgColor[0], bgColor[2]); // Swap Blue and Red
283
+ }
284
+
285
+ // Create canvas with correct format based on output channel format
286
+ int canvasType = CV_8UC3; // Default to 3 channels (BGR)
287
+ if (canvasChannel_ == "BGRA" || canvasChannel_ == "RGBA") {
288
+ canvasType = CV_8UC4;
289
+ bgColor = cv::Scalar(bgColor[0], bgColor[1], bgColor[2], 255); // Add alpha channel
290
+ } else if (canvasChannel_ == "GRAY") {
291
+ canvasType = CV_8UC1;
292
+ bgColor = cv::Scalar((bgColor[0] + bgColor[1] + bgColor[2]) / 3.0); // Convert to grayscale
293
+ }
294
+
295
+ canvas_ = cv::Mat(canvasHeight_, canvasWidth_, canvasType, bgColor);
296
+
297
+ // Process all image configurations in Z-order
298
+ for (const auto& config : imageConfigs_) {
299
+ ProcessImageFast(config);
300
+ }
301
+
302
+ taskMs_ = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
303
+
304
+ /* ─ SUPER FAST multi-format encoding (optional) ─ */
305
+ if (outputFormat_ != "raw") {
306
+ // Convert to BGR format for encoding if needed
307
+ const cv::Mat& srcForEncoding = (canvasChannel_ == "BGR") ? canvas_
308
+ : ToBgrForJpg(canvas_, canvasChannel_);
309
+ encodeMs_ = EncodeToFormat(srcForEncoding, encodedBuf_, outputFormat_, quality_, pngOptimize_);
310
+ }
311
+ }
312
+
313
+ void OnOK() override {
314
+ Napi::Env env = Env();
315
+
316
+ // Zero-copy output creation with correct channel format
317
+ Napi::Value jsImg = (outputFormat_ != "raw")
318
+ ? VectorToBuffer(env, std::move(encodedBuf_)) // Zero-copy encoded
319
+ : MatToRawJS(env, canvas_.clone(), canvasChannel_); // Contiguous raw with correct channel format
320
+
321
+ Napi::Object result = Napi::Object::New(env);
322
+ result.Set("image", jsImg);
323
+ result.Set("timing", MakeTimingJS(env, convertMs_, taskMs_, encodeMs_));
324
+
325
+ if (hasMasks_) {
326
+ Napi::Array outMasks = Napi::Array::New(env);
327
+ uint32_t outIdx = 0;
328
+ for (size_t i = 0; i < maskOutputs_.size(); i++) {
329
+ if (maskOutputs_[i].empty()) continue;
330
+ Napi::Object maskObj = Napi::Object::New(env);
331
+ maskObj.Set("mask", MatToRawJS(env, maskOutputs_[i], "GRAY"));
332
+ if (!maskTags_[i].empty()) {
333
+ maskObj.Set("tag", Napi::String::New(env, maskTags_[i]));
334
+ }
335
+ outMasks.Set(outIdx++, maskObj);
336
+ }
337
+ result.Set("masks", outMasks);
338
+ }
339
+
340
+ Callback().Call({ env.Null(), result });
341
+ }
342
+
343
+ void OnError(const Napi::Error& e) override {
344
+ Callback().Call({ e.Value(), Env().Null() });
345
+ }
346
+
347
+ private:
348
+ struct ImageConfig {
349
+ int arrayIndex;
350
+ double x, y;
351
+ double rotation;
352
+ int width, height; // -1 means keep original
353
+ int zIndex;
354
+ };
355
+
356
+ // ULTRA-FAST image processing with transformations
357
+ void ProcessImageFast(const ImageConfig& config) {
358
+ if (config.arrayIndex < 0 || config.arrayIndex >= static_cast<int>(images_.size())) {
359
+ return; // Skip invalid indices
360
+ }
361
+
362
+ const bool hasMaskForImage = hasMasks_ &&
363
+ config.arrayIndex < static_cast<int>(masks_.size()) &&
364
+ !masks_[config.arrayIndex].empty();
365
+
366
+ cv::Mat img = images_[config.arrayIndex].clone(); // Work with copy for transformations
367
+ cv::Mat mask = hasMaskForImage ? masks_[config.arrayIndex].clone() : cv::Mat();
368
+ if (img.empty()) return;
369
+
370
+ const std::string& imgChannel = imageChannels_[config.arrayIndex];
371
+
372
+ // Step 1: Resize if needed
373
+ if (config.width > 0 || config.height > 0) {
374
+ int targetWidth = config.width > 0 ? config.width : img.cols;
375
+ int targetHeight = config.height > 0 ? config.height : img.rows;
376
+
377
+ // Maintain aspect ratio if only one dimension specified
378
+ if (config.width > 0 && config.height <= 0) {
379
+ targetHeight = static_cast<int>(std::round(targetWidth * static_cast<double>(img.rows) / img.cols));
380
+ } else if (config.height > 0 && config.width <= 0) {
381
+ targetWidth = static_cast<int>(std::round(targetHeight * static_cast<double>(img.cols) / img.rows));
382
+ }
383
+
384
+ cv::resize(img, img, cv::Size(targetWidth, targetHeight), 0, 0, cv::INTER_LINEAR);
385
+ if (hasMaskForImage && !mask.empty()) {
386
+ cv::resize(mask, mask, cv::Size(targetWidth, targetHeight), 0, 0, cv::INTER_NEAREST);
387
+ }
388
+ }
389
+
390
+ // Step 2: Rotate if needed
391
+ if (std::abs(config.rotation) > 1e-3) {
392
+ // Fast-path for 90-degree rotations
393
+ double normalizedAngle = std::fmod(config.rotation + 360.0, 360.0);
394
+ double eps = 1e-3;
395
+
396
+ if (std::abs(normalizedAngle) < eps || std::abs(normalizedAngle - 360.0) < eps) {
397
+ // 0 degrees - no rotation needed
398
+ } else if (std::abs(normalizedAngle - 90.0) < eps) {
399
+ // 90° counterclockwise (mathematical standard)
400
+ cv::rotate(img, img, cv::ROTATE_90_COUNTERCLOCKWISE);
401
+ } else if (std::abs(normalizedAngle - 180.0) < eps) {
402
+ cv::rotate(img, img, cv::ROTATE_180);
403
+ } else if (std::abs(normalizedAngle - 270.0) < eps) {
404
+ // 270° counterclockwise = 90° clockwise
405
+ cv::rotate(img, img, cv::ROTATE_90_CLOCKWISE);
406
+ } else {
407
+ // Arbitrary angles - use affine transformation
408
+ // Negate rotation to make positive angles counterclockwise (mathematical standard)
409
+ // OpenCV uses clockwise positive, so we negate to get counterclockwise positive
410
+ int w = img.cols, h = img.rows;
411
+ cv::Point2f center(w / 2.0f, h / 2.0f);
412
+ cv::Mat rotationMatrix = cv::getRotationMatrix2D(center, -config.rotation, 1.0);
413
+
414
+ // Calculate new bounding box to prevent cropping
415
+ double cosA = std::abs(rotationMatrix.at<double>(0, 0));
416
+ double sinA = std::abs(rotationMatrix.at<double>(0, 1));
417
+ cv::Size newSize(static_cast<int>(h * sinA + w * cosA),
418
+ static_cast<int>(h * cosA + w * sinA));
419
+
420
+ // Adjust translation to center the rotated image
421
+ rotationMatrix.at<double>(0, 2) += newSize.width / 2.0 - center.x;
422
+ rotationMatrix.at<double>(1, 2) += newSize.height / 2.0 - center.y;
423
+
424
+ // Use transparent padding for rotation to allow layering effects
425
+ // This allows background images to show through the rotation padding areas
426
+ cv::Scalar padColor(0, 0, 0, 0); // Transparent black (RGBA)
427
+
428
+ // Ensure the image has an alpha channel for transparent padding
429
+ // Respect original colorSpace format to prevent channel inversion
430
+ if (img.channels() == 3) {
431
+ if (imgChannel == "RGB") {
432
+ cv::cvtColor(img, img, cv::COLOR_RGB2RGBA);
433
+ } else { // BGR format
434
+ cv::cvtColor(img, img, cv::COLOR_BGR2BGRA);
435
+ }
436
+ } else if (img.channels() == 1) {
437
+ cv::cvtColor(img, img, cv::COLOR_GRAY2BGRA);
438
+ }
439
+ // 4-channel images (RGBA/BGRA) already have alpha - no conversion needed
440
+
441
+ cv::warpAffine(img, img, rotationMatrix, newSize,
442
+ cv::INTER_LINEAR, cv::BORDER_CONSTANT, padColor);
443
+ if (hasMaskForImage && !mask.empty()) {
444
+ cv::warpAffine(mask, mask, rotationMatrix, newSize,
445
+ cv::INTER_NEAREST, cv::BORDER_CONSTANT, cv::Scalar(0));
446
+ }
447
+ }
448
+ }
449
+
450
+ // Step 3: Place on canvas
451
+ // Update channel format if we converted for rotation
452
+ std::string finalImgChannel = imgChannel;
453
+ if (config.rotation && std::abs(config.rotation) > 1e-3) {
454
+ // After rotation with transparent padding, track correct format
455
+ if (img.channels() == 4) {
456
+ // Preserve original color order for all input formats
457
+ if (imgChannel == "RGB") {
458
+ finalImgChannel = "RGBA";
459
+ } else if (imgChannel == "BGR") {
460
+ finalImgChannel = "BGRA";
461
+ } else if (imgChannel == "GRAY") {
462
+ finalImgChannel = "BGRA"; // GRAY converts to BGRA
463
+ }
464
+ // RGBA and BGRA inputs remain unchanged
465
+ }
466
+ }
467
+
468
+ PlaceImageOnCanvas(img, config, finalImgChannel);
469
+ if (hasMaskForImage && !mask.empty()) {
470
+ PlaceMaskOnCanvas(mask, config);
471
+ }
472
+ }
473
+
474
+ // ULTRA-FAST image placement with bounds checking
475
+ void PlaceImageOnCanvas(const cv::Mat& img, const ImageConfig& config, const std::string& imgChannel) {
476
+ if (img.empty()) return;
477
+
478
+ // Calculate position - FAST integer operations
479
+ int x = normalized_ ? static_cast<int>(std::round(config.x * canvasWidth_))
480
+ : static_cast<int>(std::lround(config.x));
481
+ int y = normalized_ ? static_cast<int>(std::round(config.y * canvasHeight_))
482
+ : static_cast<int>(std::lround(config.y));
483
+
484
+ // FAST bounds checking with early exit
485
+ if (x >= canvasWidth_ || y >= canvasHeight_) return;
486
+ if (x + img.cols <= 0 || y + img.rows <= 0) return;
487
+
488
+ // Calculate intersection rectangle - OPTIMIZED
489
+ int srcX = std::max(0, -x);
490
+ int srcY = std::max(0, -y);
491
+ int dstX = std::max(0, x);
492
+ int dstY = std::max(0, y);
493
+
494
+ int width = std::min(img.cols - srcX, canvasWidth_ - dstX);
495
+ int height = std::min(img.rows - srcY, canvasHeight_ - dstY);
496
+
497
+ if (width <= 0 || height <= 0) return;
498
+
499
+ // ZERO-COPY image placement using OpenCV's optimized copyTo
500
+ cv::Rect srcROI(srcX, srcY, width, height);
501
+ cv::Rect dstROI(dstX, dstY, width, height);
502
+
503
+ // Convert input image to match canvas format
504
+ cv::Mat imgToPlace;
505
+ cv::Mat srcRegion = img(srcROI);
506
+
507
+ // Convert input image to match canvas format
508
+ if (canvasChannel_ == "GRAY") {
509
+ // Convert to grayscale canvas
510
+ if (imgChannel == "GRAY") {
511
+ imgToPlace = srcRegion;
512
+ } else if (imgChannel == "RGB") {
513
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGB2GRAY);
514
+ } else if (imgChannel == "RGBA") {
515
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGBA2GRAY);
516
+ } else if (imgChannel == "BGRA") {
517
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGRA2GRAY);
518
+ } else {
519
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGR2GRAY);
520
+ }
521
+ } else if (canvasChannel_ == "BGR") {
522
+ // Convert to BGR canvas
523
+ if (imgChannel == "GRAY") {
524
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_GRAY2BGR);
525
+ } else if (imgChannel == "RGB") {
526
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGB2BGR);
527
+ } else if (imgChannel == "RGBA") {
528
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGBA2BGR);
529
+ } else if (imgChannel == "BGRA") {
530
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGRA2BGR);
531
+ } else {
532
+ imgToPlace = srcRegion; // Already BGR
533
+ }
534
+ } else if (canvasChannel_ == "RGB") {
535
+ // Convert to RGB canvas
536
+ if (imgChannel == "GRAY") {
537
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_GRAY2RGB);
538
+ } else if (imgChannel == "RGB") {
539
+ imgToPlace = srcRegion; // Already RGB
540
+ } else if (imgChannel == "RGBA") {
541
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGBA2RGB);
542
+ } else if (imgChannel == "BGRA") {
543
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGRA2RGB);
544
+ } else {
545
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGR2RGB);
546
+ }
547
+ } else if (canvasChannel_ == "BGRA") {
548
+ // Convert to BGRA canvas
549
+ if (imgChannel == "GRAY") {
550
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_GRAY2BGRA);
551
+ } else if (imgChannel == "RGB") {
552
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGB2BGRA);
553
+ } else if (imgChannel == "RGBA") {
554
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGBA2BGRA);
555
+ } else if (imgChannel == "BGRA") {
556
+ imgToPlace = srcRegion; // Already BGRA
557
+ } else {
558
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGR2BGRA);
559
+ }
560
+ } else if (canvasChannel_ == "RGBA") {
561
+ // Convert to RGBA canvas
562
+ if (imgChannel == "GRAY") {
563
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_GRAY2RGBA);
564
+ } else if (imgChannel == "RGB") {
565
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGB2RGBA);
566
+ } else if (imgChannel == "RGBA") {
567
+ imgToPlace = srcRegion; // Already RGBA
568
+ } else if (imgChannel == "BGRA") {
569
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGRA2RGBA);
570
+ } else {
571
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGR2RGBA);
572
+ }
573
+ } else {
574
+ // Default to BGR conversion
575
+ if (imgChannel == "GRAY") {
576
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_GRAY2BGR);
577
+ } else if (imgChannel == "RGB") {
578
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGB2BGR);
579
+ } else if (imgChannel == "RGBA") {
580
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_RGBA2BGR);
581
+ } else if (imgChannel == "BGRA") {
582
+ cv::cvtColor(srcRegion, imgToPlace, cv::COLOR_BGRA2BGR);
583
+ } else {
584
+ imgToPlace = srcRegion;
585
+ }
586
+ }
587
+
588
+ // Alpha-aware image placement for transparent rotation padding
589
+ if (imgToPlace.channels() == 4 && canvasChannel_ == "RGBA") {
590
+ // Both source and destination have alpha - use proper alpha blending
591
+ cv::Mat canvasROI = canvas_(dstROI);
592
+
593
+ // Custom alpha blending for maximum control
594
+ for (int y = 0; y < imgToPlace.rows; ++y) {
595
+ for (int x = 0; x < imgToPlace.cols; ++x) {
596
+ cv::Vec4b& srcPixel = imgToPlace.at<cv::Vec4b>(y, x);
597
+ cv::Vec4b& dstPixel = canvasROI.at<cv::Vec4b>(y, x);
598
+
599
+ float srcAlpha = srcPixel[3] / 255.0f;
600
+ float dstAlpha = dstPixel[3] / 255.0f;
601
+
602
+ if (srcAlpha > 0.0f) {
603
+ // Alpha blending formula: dst = src * srcAlpha + dst * (1 - srcAlpha) * dstAlpha
604
+ float outAlpha = srcAlpha + dstAlpha * (1.0f - srcAlpha);
605
+
606
+ if (outAlpha > 0.0f) {
607
+ dstPixel[0] = static_cast<uchar>((srcPixel[0] * srcAlpha + dstPixel[0] * dstAlpha * (1.0f - srcAlpha)) / outAlpha);
608
+ dstPixel[1] = static_cast<uchar>((srcPixel[1] * srcAlpha + dstPixel[1] * dstAlpha * (1.0f - srcAlpha)) / outAlpha);
609
+ dstPixel[2] = static_cast<uchar>((srcPixel[2] * srcAlpha + dstPixel[2] * dstAlpha * (1.0f - srcAlpha)) / outAlpha);
610
+ dstPixel[3] = static_cast<uchar>(outAlpha * 255.0f);
611
+ }
612
+ }
613
+ }
614
+ }
615
+ } else {
616
+ // Standard copy operation for non-alpha images
617
+ imgToPlace.copyTo(canvas_(dstROI));
618
+ }
619
+ }
620
+
621
+ void PlaceMaskOnCanvas(const cv::Mat& mask, const ImageConfig& config) {
622
+ if (mask.empty()) return;
623
+ if (config.arrayIndex < 0 || config.arrayIndex >= static_cast<int>(maskOutputs_.size())) return;
624
+
625
+ if (maskOutputs_[config.arrayIndex].empty()) {
626
+ maskOutputs_[config.arrayIndex] = cv::Mat::zeros(canvasHeight_, canvasWidth_, CV_8UC1);
627
+ }
628
+
629
+ int x = normalized_ ? static_cast<int>(std::round(config.x * canvasWidth_))
630
+ : static_cast<int>(std::lround(config.x));
631
+ int y = normalized_ ? static_cast<int>(std::round(config.y * canvasHeight_))
632
+ : static_cast<int>(std::lround(config.y));
633
+
634
+ if (x >= canvasWidth_ || y >= canvasHeight_) return;
635
+ if (x + mask.cols <= 0 || y + mask.rows <= 0) return;
636
+
637
+ int srcX = std::max(0, -x);
638
+ int srcY = std::max(0, -y);
639
+ int dstX = std::max(0, x);
640
+ int dstY = std::max(0, y);
641
+
642
+ int width = std::min(mask.cols - srcX, canvasWidth_ - dstX);
643
+ int height = std::min(mask.rows - srcY, canvasHeight_ - dstY);
644
+
645
+ if (width <= 0 || height <= 0) return;
646
+
647
+ cv::Rect srcROI(srcX, srcY, width, height);
648
+ cv::Rect dstROI(dstX, dstY, width, height);
649
+
650
+ cv::Mat srcRegion = mask(srcROI);
651
+ cv::Mat dstRegion = maskOutputs_[config.arrayIndex](dstROI);
652
+
653
+ cv::max(dstRegion, srcRegion, dstRegion);
654
+ }
655
+
656
+ // Member variables
657
+ std::vector<cv::Mat> images_;
658
+ std::vector<std::string> imageChannels_;
659
+ std::vector<ImageConfig> imageConfigs_;
660
+ cv::Mat canvas_;
661
+ std::string canvasChannel_;
662
+ std::vector<cv::Mat> masks_;
663
+ std::vector<std::string> maskTags_;
664
+ std::vector<cv::Mat> maskOutputs_;
665
+ bool hasMasks_{false};
666
+
667
+ int canvasWidth_, canvasHeight_;
668
+ std::string backgroundColor_;
669
+ bool normalized_;
670
+ std::string outputFormat_;
671
+ int quality_;
672
+ bool pngOptimize_;
673
+
674
+ double convertMs_{0.0}, taskMs_{0.0}, encodeMs_{0.0};
675
+ std::vector<uchar> encodedBuf_;
676
+ };
677
+
678
+ /*──────── BINDING: advancedMosaic(imagesArray, width, height, bgColor, imageConfigs, normalized, [options|outputFormat], ...) ─*/
679
+ Napi::Value AdvancedMosaic(const Napi::CallbackInfo& info) {
680
+ Napi::Env env = info.Env();
681
+
682
+ if (info.Length() < 7 || !info[info.Length() - 1].IsFunction()) {
683
+ return Napi::TypeError::New(env,
684
+ "advancedMosaic(imagesArray, width, height, bgColor, imageConfigs, normalized, [options|outputFormat], [quality], [pngOptimize], callback)")
685
+ .Value();
686
+ }
687
+
688
+ // Parse required parameters
689
+ int i = 0;
690
+ Napi::Array imagesArray = info[i++].As<Napi::Array>();
691
+ int canvasWidth = info[i++].As<Napi::Number>().Int32Value();
692
+ int canvasHeight = info[i++].As<Napi::Number>().Int32Value();
693
+ std::string backgroundColor = info[i++].As<Napi::String>().Utf8Value();
694
+ Napi::Array imageConfigs = info[i++].As<Napi::Array>();
695
+ bool normalized = info[i++].As<Napi::Boolean>().Value();
696
+
697
+ // Optional parameters (either legacy positional or options object)
698
+ std::string outputFormat = "raw";
699
+ int quality = 90;
700
+ bool pngOptimize = false;
701
+ bool hasMasks = false;
702
+ Napi::Array masksArray;
703
+
704
+ // If next argument is an object (not array/function), treat it as options
705
+ if (info.Length() - i > 1 && info[i].IsObject() && !info[i].IsArray() && !info[i].IsFunction()) {
706
+ Napi::Object opts = info[i++].As<Napi::Object>();
707
+ if (opts.Has("outputFormat")) outputFormat = opts.Get("outputFormat").As<Napi::String>().Utf8Value();
708
+ if (opts.Has("quality")) quality = opts.Get("quality").As<Napi::Number>().Int32Value();
709
+ if (opts.Has("pngOptimize")) pngOptimize = opts.Get("pngOptimize").As<Napi::Boolean>().Value();
710
+ if (opts.Has("masks") && opts.Get("masks").IsArray()) {
711
+ masksArray = opts.Get("masks").As<Napi::Array>();
712
+ hasMasks = true;
713
+ }
714
+ }
715
+
716
+ // Legacy positional parsing
717
+ if (info.Length() - i >= 2) {
718
+ outputFormat = info[i++].As<Napi::String>().Utf8Value();
719
+ }
720
+ if (info.Length() - i >= 2) {
721
+ quality = info[i++].As<Napi::Number>().Int32Value();
722
+ }
723
+ if (info.Length() - i >= 2) {
724
+ pngOptimize = info[i++].As<Napi::Boolean>().Value();
725
+ }
726
+
727
+ Napi::Function callback = info[info.Length() - 1].As<Napi::Function>();
728
+
729
+ // Validate canvas dimensions
730
+ if (canvasWidth <= 0 || canvasHeight <= 0) {
731
+ return Napi::TypeError::New(env, "Canvas dimensions must be positive").Value();
732
+ }
733
+
734
+ // Launch ULTRA-FAST worker
735
+ (new AdvancedMosaicWorker(callback, imagesArray, canvasWidth, canvasHeight,
736
+ backgroundColor, imageConfigs, normalized, outputFormat, quality, pngOptimize,
737
+ hasMasks, masksArray))->Queue();
738
+
739
+ return env.Undefined();
740
+ }