@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,638 @@
1
+ #include <napi.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "utils.h"
4
+ #include <unordered_map>
5
+ #include <random>
6
+ #include <cmath>
7
+ #include <algorithm>
8
+ // OpenMP is only used via pragmas; header is not required unless functions are called.
9
+ // We avoid including it to keep macOS builds (without libomp headers) happy.
10
+ // #include <omp.h>
11
+
12
+ #if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)
13
+ #include <immintrin.h> // AVX2 intrinsics (not used on non-x86 builds)
14
+ #endif
15
+
16
+ // Optimized structure to hold mask information
17
+ struct OptimizedMaskInfo {
18
+ cv::Mat binaryMask; // Pre-computed binary mask
19
+ cv::Rect boundingBox; // Bounding box for the mask
20
+ cv::Vec3f normalizedColor; // Pre-normalized color (0-1 range)
21
+ std::vector<cv::Point> pixelPoints; // Actual polygon points in pixels
22
+ std::string className;
23
+ int priority; // Priority for overlap resolution (lower = higher priority)
24
+ int originalIndex; // Original input order for tie-breaking
25
+ };
26
+
27
+ // Optimized polygon mask creation with bounding box
28
+ inline std::pair<cv::Mat, cv::Rect> CreateOptimizedPolygonMask(
29
+ const std::vector<cv::Point2f>& polygon,
30
+ cv::Size imageSize) {
31
+
32
+ // Convert to pixel coordinates and find bounding box
33
+ std::vector<cv::Point> pixelPolygon;
34
+ pixelPolygon.reserve(polygon.size());
35
+
36
+ int minX = imageSize.width, maxX = 0;
37
+ int minY = imageSize.height, maxY = 0;
38
+
39
+ for (const auto& point : polygon) {
40
+ int x = static_cast<int>(point.x * imageSize.width);
41
+ int y = static_cast<int>(point.y * imageSize.height);
42
+
43
+ x = std::max(0, std::min(imageSize.width - 1, x));
44
+ y = std::max(0, std::min(imageSize.height - 1, y));
45
+
46
+ pixelPolygon.emplace_back(x, y);
47
+
48
+ minX = std::min(minX, x);
49
+ maxX = std::max(maxX, x);
50
+ minY = std::min(minY, y);
51
+ maxY = std::max(maxY, y);
52
+ }
53
+
54
+ // Create bounding box
55
+ cv::Rect bbox(minX, minY, maxX - minX + 1, maxY - minY + 1);
56
+
57
+ // Create mask only for bounding box region
58
+ cv::Mat mask = cv::Mat::zeros(bbox.size(), CV_8UC1);
59
+
60
+ // Adjust polygon coordinates to bounding box
61
+ std::vector<cv::Point> adjustedPolygon;
62
+ for (const auto& pt : pixelPolygon) {
63
+ adjustedPolygon.emplace_back(pt.x - minX, pt.y - minY);
64
+ }
65
+
66
+ const cv::Point* pts = adjustedPolygon.data();
67
+ int npts = static_cast<int>(adjustedPolygon.size());
68
+ cv::fillPoly(mask, &pts, &npts, 1, cv::Scalar(255), cv::LINE_4); // LINE_4 is faster than LINE_AA
69
+
70
+ return {mask, bbox};
71
+ }
72
+
73
+ // Optimized color generation (cached)
74
+ static std::unordered_map<std::string, cv::Vec3f> colorCache;
75
+
76
+ // Resolve class name from common field names
77
+ inline std::string ExtractClassName(const Napi::Object& obj) {
78
+ const std::vector<std::string> keys = {"tag", "class_name", "className", "label", "class"};
79
+ for (const auto& key : keys) {
80
+ if (obj.Has(key) && obj.Get(key).IsString()) {
81
+ std::string value = obj.Get(key).As<Napi::String>().Utf8Value();
82
+ if (!value.empty()) return value;
83
+ }
84
+ }
85
+ return "";
86
+ }
87
+
88
+ inline cv::Mat BuildMaskFrom2DArray(const Napi::Array& rows) {
89
+ const uint32_t rowCount = rows.Length();
90
+ if (rowCount == 0) return cv::Mat();
91
+
92
+ int cols = -1;
93
+ for (uint32_t y = 0; y < rowCount; y++) {
94
+ if (rows.Get(y).IsArray()) {
95
+ cols = static_cast<int>(rows.Get(y).As<Napi::Array>().Length());
96
+ if (cols > 0) break;
97
+ }
98
+ }
99
+ if (cols <= 0) return cv::Mat();
100
+
101
+ cv::Mat mask(rowCount, cols, CV_8UC1, cv::Scalar(0));
102
+ for (uint32_t y = 0; y < rowCount; y++) {
103
+ if (!rows.Get(y).IsArray()) continue;
104
+ Napi::Array row = rows.Get(y).As<Napi::Array>();
105
+ const uint32_t rowLen = row.Length();
106
+ for (uint32_t x = 0; x < rowLen && x < static_cast<uint32_t>(cols); x++) {
107
+ if (row.Get(x).IsNumber()) {
108
+ double v = row.Get(x).As<Napi::Number>().DoubleValue();
109
+ if (std::isfinite(v) && v != 0.0) {
110
+ double scaled = v > 1.0 ? v : v * 255.0;
111
+ mask.at<uchar>(y, x) = static_cast<uchar>(std::clamp(scaled, 0.0, 255.0));
112
+ }
113
+ }
114
+ }
115
+ }
116
+ return mask;
117
+ }
118
+
119
+ // Handles either a 2D mask matrix or an array of matrices (uses the first valid one)
120
+ inline cv::Mat ConvertMaskArrayToMat(const Napi::Array& arr) {
121
+ if (arr.Length() == 0) return cv::Mat();
122
+
123
+ Napi::Value first = arr.Get(0u);
124
+ if (first.IsArray()) {
125
+ Napi::Array firstArr = first.As<Napi::Array>();
126
+ if (firstArr.Length() > 0 && firstArr.Get(0u).IsArray()) {
127
+ // Array of masks -> pick the first valid one
128
+ for (uint32_t i = 0; i < arr.Length(); i++) {
129
+ if (!arr.Get(i).IsArray()) continue;
130
+ cv::Mat candidate = BuildMaskFrom2DArray(arr.Get(i).As<Napi::Array>());
131
+ if (!candidate.empty()) return candidate;
132
+ }
133
+ return cv::Mat();
134
+ }
135
+ }
136
+
137
+ return BuildMaskFrom2DArray(arr);
138
+ }
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
+ }
159
+
160
+ cv::Mat binary;
161
+ cv::threshold(singleChannel, binary, 0, 255, cv::THRESH_BINARY);
162
+
163
+ if (binary.size() != targetSize) {
164
+ cv::resize(binary, binary, targetSize, 0, 0, cv::INTER_NEAREST);
165
+ }
166
+
167
+ return binary;
168
+ } catch (const Napi::Error&) {
169
+ return cv::Mat();
170
+ } catch (...) {
171
+ return cv::Mat();
172
+ }
173
+ }
174
+
175
+ inline cv::Mat NormalizeMaskBinary(cv::Mat mask, const cv::Size& targetSize) {
176
+ if (mask.empty()) return mask;
177
+
178
+ if (mask.channels() > 1) {
179
+ cv::Mat gray;
180
+ cv::cvtColor(mask, gray, cv::COLOR_BGR2GRAY);
181
+ mask = gray;
182
+ }
183
+
184
+ if (mask.depth() != CV_8U) {
185
+ cv::Mat tmp;
186
+ mask.convertTo(tmp, CV_8U, 255.0);
187
+ mask = tmp;
188
+ }
189
+
190
+ cv::Mat binary;
191
+ cv::threshold(mask, binary, 0, 255, cv::THRESH_BINARY);
192
+
193
+ if (binary.size() != targetSize) {
194
+ cv::resize(binary, binary, targetSize, 0, 0, cv::INTER_NEAREST);
195
+ }
196
+
197
+ return binary;
198
+ }
199
+
200
+ // Generate maximally different color from existing colors
201
+ inline cv::Vec3f GenerateMaximallyDifferentColor(
202
+ const std::string& className,
203
+ const std::unordered_map<std::string, cv::Vec3f>& userColors) {
204
+
205
+ // Collect all used colors
206
+ std::vector<cv::Vec3f> usedColors;
207
+ for (const auto& [_, color] : userColors) {
208
+ usedColors.push_back(color);
209
+ }
210
+ for (const auto& [_, color] : colorCache) {
211
+ usedColors.push_back(color);
212
+ }
213
+
214
+ // If no existing colors, start with a vivid red
215
+ if (usedColors.empty()) {
216
+ cv::Vec3f firstColor(0.0f, 0.0f, 1.0f); // BGR: pure red
217
+ colorCache[className] = firstColor;
218
+ return firstColor;
219
+ }
220
+
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
+ }
244
+
245
+ // Find candidate with maximum minimum distance to existing colors
246
+ float maxMinDistance = 0;
247
+ cv::Vec3f bestColor = candidates[0];
248
+
249
+ for (const auto& candidate : candidates) {
250
+ float minDistance = std::numeric_limits<float>::max();
251
+
252
+ for (const auto& existing : usedColors) {
253
+ // Calculate perceptual color distance with weighted components
254
+ // Human eye is more sensitive to green, then red, then blue
255
+ float dist = sqrt(
256
+ pow((candidate[2] - existing[2]) * 2.0f, 2) + // Red (BGR[2])
257
+ pow((candidate[1] - existing[1]) * 3.0f, 2) + // Green (BGR[1])
258
+ pow((candidate[0] - existing[0]) * 1.0f, 2) // Blue (BGR[0])
259
+ );
260
+ minDistance = std::min(minDistance, dist);
261
+ }
262
+
263
+ if (minDistance > maxMinDistance) {
264
+ maxMinDistance = minDistance;
265
+ bestColor = candidate;
266
+ }
267
+ }
268
+
269
+ // Cache and return
270
+ colorCache[className] = bestColor;
271
+ return bestColor;
272
+ }
273
+
274
+ inline cv::Vec3f GetCachedColor(const std::string& className) {
275
+ auto it = colorCache.find(className);
276
+ if (it != colorCache.end()) {
277
+ return it->second;
278
+ }
279
+
280
+ // This should not be called anymore, but keep as fallback
281
+ cv::Vec3f color(1.0f, 1.0f, 1.0f); // White fallback
282
+ colorCache[className] = color;
283
+ return color;
284
+ }
285
+
286
+ /*------------------------------------------------------------------------*/
287
+ class AddMasksOptimizedWorker final : public Napi::AsyncWorker {
288
+ public:
289
+ AddMasksOptimizedWorker(Napi::Function cb,
290
+ const Napi::Value& jsImg,
291
+ const Napi::Array& masksArray,
292
+ const Napi::Object& classColorMap,
293
+ const Napi::Array& classPriorityOrder,
294
+ double maskStrength,
295
+ bool autoGenerateColors,
296
+ std::string outputFormat,
297
+ int quality = 90,
298
+ bool pngOptimize = false)
299
+ : Napi::AsyncWorker(cb),
300
+ maskStrength(static_cast<float>(maskStrength)),
301
+ autoGenerateColors(autoGenerateColors),
302
+ outputFormat(std::move(outputFormat)),
303
+ quality(quality), pngOptimize(pngOptimize)
304
+ {
305
+ const int64 t0 = cv::getTickCount();
306
+
307
+ // Convert JavaScript image to OpenCV Mat
308
+ imageMat = ConvertToMat(jsImg);
309
+
310
+ // Build priority map from ordered array (lower index = higher priority)
311
+ std::unordered_map<std::string, int> priorityMap;
312
+ for (size_t i = 0; i < classPriorityOrder.Length(); i++) {
313
+ if (classPriorityOrder.Get(i).IsString()) {
314
+ std::string cls = classPriorityOrder.Get(i).As<Napi::String>().Utf8Value();
315
+ priorityMap[cls] = static_cast<int>(i);
316
+ }
317
+ }
318
+
319
+ // Parse class color map
320
+ std::unordered_map<std::string, cv::Vec3f> userColorMap;
321
+ Napi::Array colorMapKeys = classColorMap.GetPropertyNames();
322
+ for (size_t i = 0; i < colorMapKeys.Length(); i++) {
323
+ std::string className = colorMapKeys.Get(i).As<Napi::String>().Utf8Value();
324
+ std::string hexColor = classColorMap.Get(className).As<Napi::String>().Utf8Value();
325
+
326
+ if (hexColor.length() == 7 && hexColor[0] == '#') {
327
+ float r = std::stoi(hexColor.substr(1, 2), nullptr, 16) / 255.0f;
328
+ float g = std::stoi(hexColor.substr(3, 2), nullptr, 16) / 255.0f;
329
+ float b = std::stoi(hexColor.substr(5, 2), nullptr, 16) / 255.0f;
330
+ userColorMap[className] = cv::Vec3f(b, g, r); // BGR for OpenCV
331
+ }
332
+ }
333
+
334
+ auto resolveColor = [&](const std::string& className) -> cv::Vec3f {
335
+ auto colorIt = userColorMap.find(className);
336
+ if (colorIt != userColorMap.end()) {
337
+ return colorIt->second;
338
+ }
339
+
340
+ auto cachedColorIt = colorCache.find(className);
341
+ if (cachedColorIt != colorCache.end()) {
342
+ return cachedColorIt->second;
343
+ }
344
+
345
+ if (autoGenerateColors) {
346
+ return GenerateMaximallyDifferentColor(className, userColorMap);
347
+ }
348
+
349
+ return cv::Vec3f(1.0f, 1.0f, 1.0f);
350
+ };
351
+
352
+ // Lambda to resolve priority for a class name
353
+ auto resolvePriority = [&](const std::string& className, int originalIndex) -> int {
354
+ auto it = priorityMap.find(className);
355
+ if (it != priorityMap.end()) {
356
+ return it->second; // Mapped class: use priority from order
357
+ }
358
+ // Unmapped class: use INT_MAX base + original index for tie-breaking
359
+ return INT_MAX / 2 + originalIndex;
360
+ };
361
+
362
+ // Pre-process all masks and create optimized structures
363
+ for (size_t maskIndex = 0; maskIndex < masksArray.Length(); maskIndex++) {
364
+ if (!masksArray.Get(maskIndex).IsObject()) continue;
365
+ Napi::Object maskObj = masksArray.Get(maskIndex).As<Napi::Object>();
366
+
367
+ std::string className = ExtractClassName(maskObj);
368
+ if (className.empty()) continue;
369
+
370
+ cv::Vec3f resolvedColor = resolveColor(className);
371
+ bool addedPolygon = false;
372
+
373
+ // --- Polygons path (preferred when present) ---
374
+ if (maskObj.Has("polygons") && maskObj.Get("polygons").IsArray()) {
375
+ Napi::Array polygonsArray = maskObj.Get("polygons").As<Napi::Array>();
376
+ for (size_t polyIdx = 0; polyIdx < polygonsArray.Length(); polyIdx++) {
377
+ if (!polygonsArray.Get(polyIdx).IsArray()) {
378
+ continue;
379
+ }
380
+
381
+ Napi::Array coordinates = polygonsArray.Get(polyIdx).As<Napi::Array>();
382
+
383
+ // Parse polygon coordinates
384
+ std::vector<cv::Point2f> polygon;
385
+ polygon.reserve(coordinates.Length());
386
+
387
+ for (size_t i = 0; i < coordinates.Length(); i++) {
388
+ if (!coordinates.Get(i).IsArray()) {
389
+ continue;
390
+ }
391
+ Napi::Array point = coordinates.Get(i).As<Napi::Array>();
392
+ if (point.Length() >= 2) {
393
+ float x = point.Get(0u).As<Napi::Number>().FloatValue();
394
+ float y = point.Get(1u).As<Napi::Number>().FloatValue();
395
+ polygon.emplace_back(x, y);
396
+ }
397
+ }
398
+
399
+ 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;
413
+ }
414
+ }
415
+ }
416
+
417
+ // --- Raw mask path (inferencer 'mask' output) ---
418
+ if (!addedPolygon && maskObj.Has("mask")) {
419
+ cv::Mat maskBinary;
420
+ Napi::Value maskVal = maskObj.Get("mask");
421
+
422
+ if (maskVal.IsArray()) {
423
+ maskBinary = ConvertMaskArrayToMat(maskVal.As<Napi::Array>());
424
+ } else if (maskVal.IsBuffer() || maskVal.IsObject()) {
425
+ maskBinary = ConvertMaskImageToMat(maskVal, imageMat.size());
426
+ }
427
+
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
+ }
444
+ }
445
+ }
446
+ }
447
+
448
+ // Sort masks by priority (lower priority value = higher precedence)
449
+ // Use stable_sort to preserve original order for equal priorities
450
+ std::stable_sort(optimizedMasks.begin(), optimizedMasks.end(),
451
+ [](const OptimizedMaskInfo& a, const OptimizedMaskInfo& b) {
452
+ if (a.priority != b.priority) return a.priority < b.priority;
453
+ return a.originalIndex < b.originalIndex; // Tie-breaker: input order
454
+ });
455
+
456
+ imageFormat = DetectChannelFormatShared(jsImg, imageMat);
457
+ outputChannel = imageFormat;
458
+
459
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
460
+ }
461
+
462
+ protected:
463
+ void Execute() override {
464
+ const int64 t0 = cv::getTickCount();
465
+
466
+ // Convert image to target format
467
+ cv::Mat img = ConvertToTargetFormatShared(imageMat, imageFormat, outputChannel);
468
+
469
+ // Early exit if no masks
470
+ if (optimizedMasks.empty()) {
471
+ result = img.clone();
472
+ taskMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
473
+
474
+ if (outputFormat != "raw") {
475
+ cv::Mat tmp = ToBgrForJpg(result, outputChannel);
476
+ encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
477
+ }
478
+ return;
479
+ }
480
+
481
+ // Work directly with uint8 for better performance
482
+ result = img.clone();
483
+ const int channels = result.channels();
484
+ const int rows = result.rows;
485
+ const int cols = result.cols;
486
+
487
+ // Pre-calculate color space conversion if needed
488
+ const bool isRGB = (outputChannel == "RGB" || outputChannel == "RGBA");
489
+
490
+ // Create painted-pixel tracking matrix (single channel, same size as image)
491
+ // Used to ensure each pixel is only painted once by the highest-priority mask
492
+ cv::Mat painted = cv::Mat::zeros(rows, cols, CV_8UC1);
493
+
494
+ // Process masks SEQUENTIALLY to respect priority order
495
+ // Masks are already sorted by priority (lower value = higher priority)
496
+ for (size_t maskIdx = 0; maskIdx < optimizedMasks.size(); maskIdx++) {
497
+ const auto& maskInfo = optimizedMasks[maskIdx];
498
+ const cv::Rect& bbox = maskInfo.boundingBox;
499
+ const cv::Mat& mask = maskInfo.binaryMask;
500
+
501
+ // Ensure bounding box is within image bounds
502
+ cv::Rect safeBbox = bbox & cv::Rect(0, 0, cols, rows);
503
+ if (safeBbox.area() == 0) continue;
504
+
505
+ // Adjust mask region if needed
506
+ cv::Mat maskRegion = mask;
507
+ if (safeBbox != bbox) {
508
+ maskRegion = mask(cv::Rect(0, 0, safeBbox.width, safeBbox.height));
509
+ }
510
+
511
+ // Get color components (pre-scaled to 0-255)
512
+ const float cr = maskInfo.normalizedColor[isRGB ? 0 : 2] * 255.0f;
513
+ const float cg = maskInfo.normalizedColor[1] * 255.0f;
514
+ const float cb = maskInfo.normalizedColor[isRGB ? 2 : 0] * 255.0f;
515
+
516
+ // Process only the bounding box region
517
+ for (int y = 0; y < safeBbox.height; y++) {
518
+ const int globalY = safeBbox.y + y;
519
+ const uchar* maskRow = maskRegion.ptr<uchar>(y);
520
+ uchar* paintedRow = painted.ptr<uchar>(globalY);
521
+ uchar* imgRow = result.ptr<uchar>(globalY);
522
+
523
+ for (int x = 0; x < safeBbox.width; x++) {
524
+ const int globalX = safeBbox.x + x;
525
+
526
+ // Skip if already painted by higher-priority mask
527
+ if (paintedRow[globalX] > 0) continue;
528
+
529
+ if (maskRow[x] > 0) {
530
+ // Mark as painted
531
+ paintedRow[globalX] = 255;
532
+
533
+ // Apply alpha blending
534
+ const float alpha = maskStrength;
535
+ const float invAlpha = 1.0f - alpha;
536
+ const int idx = globalX * channels;
537
+
538
+ if (channels == 1) {
539
+ // Grayscale
540
+ float gray = (cr + cg + cb) / 3.0f;
541
+ imgRow[idx] = static_cast<uchar>(imgRow[idx] * invAlpha + gray * alpha);
542
+ } else if (channels == 3) {
543
+ // RGB/BGR
544
+ imgRow[idx] = static_cast<uchar>(imgRow[idx] * invAlpha + cb * alpha);
545
+ imgRow[idx + 1] = static_cast<uchar>(imgRow[idx + 1] * invAlpha + cg * alpha);
546
+ imgRow[idx + 2] = static_cast<uchar>(imgRow[idx + 2] * invAlpha + cr * alpha);
547
+ } else if (channels == 4) {
548
+ // RGBA/BGRA
549
+ imgRow[idx] = static_cast<uchar>(imgRow[idx] * invAlpha + cb * alpha);
550
+ imgRow[idx + 1] = static_cast<uchar>(imgRow[idx + 1] * invAlpha + cg * alpha);
551
+ imgRow[idx + 2] = static_cast<uchar>(imgRow[idx + 2] * invAlpha + cr * alpha);
552
+ // Keep alpha channel unchanged
553
+ }
554
+ }
555
+ }
556
+ }
557
+ }
558
+
559
+ taskMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
560
+
561
+ // Multi-format encoding if needed
562
+ if (outputFormat != "raw") {
563
+ cv::Mat tmp = ToBgrForJpg(result, outputChannel);
564
+ encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
565
+ }
566
+ }
567
+
568
+ void OnOK() override {
569
+ Napi::Env env = Env();
570
+ Napi::Value jsImg = (outputFormat != "raw") ? VectorToBuffer(env, std::move(encodedBuf))
571
+ : MatToRawJS(env, result, outputChannel);
572
+
573
+ Napi::Object out = Napi::Object::New(env);
574
+ out.Set("image", jsImg);
575
+ out.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
576
+ Callback().Call({env.Null(), out});
577
+ }
578
+
579
+ private:
580
+ cv::Mat imageMat, result;
581
+ std::string imageFormat, outputChannel;
582
+ std::vector<OptimizedMaskInfo> optimizedMasks;
583
+ float maskStrength;
584
+ bool autoGenerateColors;
585
+ std::string outputFormat;
586
+ int quality;
587
+ bool pngOptimize;
588
+ double convertMs = 0, taskMs = 0, encodeMs = 0;
589
+ std::vector<uchar> encodedBuf;
590
+ };
591
+
592
+ /*------------------------------------------------------------------------*/
593
+ Napi::Value AddMasks(const Napi::CallbackInfo& info) {
594
+ Napi::Env env = info.Env();
595
+
596
+ if (info.Length() < 7 || info.Length() > 10 || !info[info.Length() - 1].IsFunction()) {
597
+ Napi::TypeError::New(env, "addMasks(image, masksArray, classColorMap, classPriorityOrder, maskStrength, autoGenerateColors, [outputFormat], [quality], [pngOptimize], callback)")
598
+ .ThrowAsJavaScriptException();
599
+ return env.Null();
600
+ }
601
+
602
+ Napi::Value jsImg = info[0];
603
+ Napi::Array masksArray = info[1].As<Napi::Array>();
604
+ Napi::Object classColorMap = info[2].As<Napi::Object>();
605
+ Napi::Array classPriorityOrder = info[3].As<Napi::Array>();
606
+ double maskStrength = info[4].As<Napi::Number>().DoubleValue();
607
+ bool autoGenerateColors = info[5].As<Napi::Boolean>().Value();
608
+
609
+ maskStrength = std::max(0.0, std::min(1.0, maskStrength));
610
+
611
+ std::string outputFormat = "raw";
612
+ int quality = 90;
613
+ bool pngOptimize = false;
614
+ size_t cbIdx = 6;
615
+
616
+ if (info.Length() >= 8) {
617
+ outputFormat = info[6].As<Napi::String>().Utf8Value();
618
+ cbIdx = 7;
619
+ }
620
+
621
+ if (info.Length() >= 9) {
622
+ quality = info[7].As<Napi::Number>().Int32Value();
623
+ cbIdx = 8;
624
+ }
625
+
626
+ if (info.Length() == 10) {
627
+ pngOptimize = info[8].As<Napi::Boolean>().Value();
628
+ cbIdx = 9;
629
+ }
630
+
631
+ (new AddMasksOptimizedWorker(
632
+ info[cbIdx].As<Napi::Function>(),
633
+ jsImg, masksArray, classColorMap, classPriorityOrder, maskStrength, autoGenerateColors,
634
+ outputFormat, quality, pngOptimize
635
+ ))->Queue();
636
+
637
+ return env.Undefined();
638
+ }