@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
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@rosepetal/node-red-contrib-image-tools",
3
+ "version": "1.1.3",
4
+ "description": "Node-RED Image Processing Toolkit",
5
+ "main": "install.sh",
6
+ "directories": {
7
+ "doc": "docs"
8
+ },
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/rosepetal-ai/node-red-contrib-image-tools.git"
15
+ },
16
+ "keywords": [
17
+ "node-red",
18
+ "image",
19
+ "opencv",
20
+ "performance"
21
+ ],
22
+ "author": "Rosepetal SL (https://www.rosepetal.ai)",
23
+ "contributors": [
24
+ {
25
+ "name": "Nil Allue",
26
+ "email": "nil.allue@rosepetal.ai"
27
+ }
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "bugs": {
31
+ "url": "https://github.com/rosepetal-ai/node-red-contrib-image-tools/issues"
32
+ },
33
+ "homepage": "https://github.com/rosepetal-ai/node-red-contrib-image-tools#readme",
34
+ "dependencies": {
35
+ "sharp": "^0.34.2"
36
+ },
37
+ "optionalDependencies": {
38
+ "@rosepetal/node-red-contrib-image-tools-linux-x64": "1.1.3",
39
+ "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.1.3",
40
+ "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.1.3",
41
+ "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.1.3",
42
+ "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.1.3"
43
+ },
44
+ "node-red": {
45
+ "version": ">=1.0.0",
46
+ "nodes": {
47
+ "image-in": "node-red-contrib-image-tools/nodes/io/image-in.js",
48
+ "folder-in": "node-red-contrib-image-tools/nodes/io/folder-in.js",
49
+ "image-out": "node-red-contrib-image-tools/nodes/io/image-out.js",
50
+ "array-in": "node-red-contrib-image-tools/nodes/io/array-in.js",
51
+ "array-out": "node-red-contrib-image-tools/nodes/io/array-out.js",
52
+ "array-select": "node-red-contrib-image-tools/nodes/io/array-select.js",
53
+ "cropBB": "node-red-contrib-image-tools/nodes/specialized/cropBB.js",
54
+ "image-align": "node-red-contrib-image-tools/nodes/specialized/image-align.js",
55
+ "resize": "node-red-contrib-image-tools/nodes/transform/resize.js",
56
+ "rotate": "node-red-contrib-image-tools/nodes/transform/rotate.js",
57
+ "crop": "node-red-contrib-image-tools/nodes/transform/crop.js",
58
+ "concat": "node-red-contrib-image-tools/nodes/mix/concat.js",
59
+ "padding": "node-red-contrib-image-tools/nodes/transform/padding.js",
60
+ "filter": "node-red-contrib-image-tools/nodes/transform/filter.js",
61
+ "draw": "node-red-contrib-image-tools/nodes/transform/draw.js",
62
+ "mosaic": "node-red-contrib-image-tools/nodes/mix/mosaic.js",
63
+ "advanced-mosaic": "node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js",
64
+ "blend": "node-red-contrib-image-tools/nodes/blend/blend.js",
65
+ "add-mask": "node-red-contrib-image-tools/nodes/blend/add-mask.js",
66
+ "add-masks": "node-red-contrib-image-tools/nodes/blend/add-masks.js",
67
+ "add-bbs": "node-red-contrib-image-tools/nodes/blend/add-bbs.js",
68
+ "queue": "node-red-contrib-image-tools/nodes/io/queue.js",
69
+ "save-file": "node-red-contrib-image-tools/nodes/io/save-file.js",
70
+ "clean-debug": "node-red-contrib-image-tools/nodes/util/clean-debug.js",
71
+ "block-detect": "node-red-contrib-image-tools/nodes/util/block-detect.js"
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,153 @@
1
+ {
2
+ "variables": {
3
+ "opencv_include_dir%": "",
4
+ "opencv_lib_dir%": ""
5
+ },
6
+ "targets": [
7
+ {
8
+ "target_name": "addon",
9
+ "sources": [
10
+ "src/main.cpp",
11
+ "src/resize.cpp",
12
+ "src/rotate.cpp",
13
+ "src/crop.cpp",
14
+ "src/concat.cpp",
15
+ "src/padding.cpp",
16
+ "src/filter.cpp",
17
+ "src/mosaic.cpp",
18
+ "src/advanced-mosaic.cpp",
19
+ "src/blend.cpp",
20
+ "src/add-mask.cpp",
21
+ "src/add-masks.cpp",
22
+ "src/add-bbs.cpp",
23
+ "src/image-align.cpp",
24
+ "src/draw.cpp"
25
+ ],
26
+ "defines": [
27
+ "NAPI_CPP_EXCEPTIONS"
28
+ ],
29
+ "conditions": [
30
+ ["opencv_lib_dir!=''", {
31
+ "include_dirs": [
32
+ "<(opencv_include_dir)",
33
+ "<!@(node -p \"require('node-addon-api').include\")"
34
+ ],
35
+ "conditions": [
36
+ ["OS=='linux'", {
37
+ "libraries": [
38
+ "<(opencv_lib_dir)/libopencv_imgcodecs.a",
39
+ "<(opencv_lib_dir)/libopencv_video.a",
40
+ "<(opencv_lib_dir)/libopencv_imgproc.a",
41
+ "<(opencv_lib_dir)/libopencv_core.a",
42
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibjpeg-turbo.a",
43
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibpng.a",
44
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibwebp.a",
45
+ "<(opencv_lib_dir)/opencv4/3rdparty/libzlib.a",
46
+ "-lpthread",
47
+ "-ldl"
48
+ ],
49
+ "cflags_cc": [
50
+ "-std=c++17",
51
+ "-O3",
52
+ "-fexceptions",
53
+ "-frtti",
54
+ "-fno-omit-frame-pointer"
55
+ ],
56
+ "ldflags": [
57
+ "-static-libgcc",
58
+ "-static-libstdc++"
59
+ ]
60
+ }],
61
+ ["OS=='mac'", {
62
+ "libraries": [
63
+ "<(opencv_lib_dir)/libopencv_imgcodecs.a",
64
+ "<(opencv_lib_dir)/libopencv_video.a",
65
+ "<(opencv_lib_dir)/libopencv_imgproc.a",
66
+ "<(opencv_lib_dir)/libopencv_core.a",
67
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibjpeg-turbo.a",
68
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibpng.a",
69
+ "<(opencv_lib_dir)/opencv4/3rdparty/liblibwebp.a",
70
+ "<(opencv_lib_dir)/opencv4/3rdparty/libzlib.a"
71
+ ],
72
+ "xcode_settings": {
73
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
74
+ "GCC_ENABLE_CPP_RTTI": "YES",
75
+ "MACOSX_DEPLOYMENT_TARGET": "10.15",
76
+ "OTHER_CPLUSPLUSFLAGS": [
77
+ "-std=c++17",
78
+ "-O3"
79
+ ]
80
+ }
81
+ }],
82
+ ["OS=='win'", {
83
+ "libraries": [
84
+ "<(opencv_lib_dir)/opencv_imgcodecs4.lib",
85
+ "<(opencv_lib_dir)/opencv_video4.lib",
86
+ "<(opencv_lib_dir)/opencv_imgproc4.lib",
87
+ "<(opencv_lib_dir)/opencv_core4.lib",
88
+ "<(opencv_lib_dir)/opencv4/3rdparty/libjpeg-turbo.lib",
89
+ "<(opencv_lib_dir)/opencv4/3rdparty/libpng.lib",
90
+ "<(opencv_lib_dir)/opencv4/3rdparty/libwebp.lib",
91
+ "<(opencv_lib_dir)/opencv4/3rdparty/zlib.lib"
92
+ ],
93
+ "msvs_settings": {
94
+ "VCCLCompilerTool": {
95
+ "RuntimeLibrary": 0,
96
+ "ExceptionHandling": 1,
97
+ "AdditionalOptions": ["/std:c++17"]
98
+ }
99
+ }
100
+ }]
101
+ ]
102
+ }, {
103
+ "include_dirs": [
104
+ "/usr/include/opencv4",
105
+ "<!@(node -p \"require('node-addon-api').include\")"
106
+ ],
107
+ "libraries": [
108
+ "<!@(pkg-config --libs --cflags opencv4)"
109
+ ],
110
+ "cflags_cc": [
111
+ "-std=c++17",
112
+ "-O3",
113
+ "-ffast-math",
114
+ "-march=native",
115
+ "-fexceptions",
116
+ "-frtti",
117
+ "-fno-omit-frame-pointer",
118
+ "-funroll-loops",
119
+ "-fstrict-aliasing",
120
+ "-fopenmp",
121
+ "-mavx2",
122
+ "-ftree-vectorize",
123
+ "-fprefetch-loop-arrays",
124
+ "-finline-functions",
125
+ "-flto",
126
+ "-fipa-pta",
127
+ "-fvect-cost-model=cheap",
128
+ "-minline-all-stringops"
129
+ ],
130
+ "ldflags": [
131
+ "-O3",
132
+ "-march=native",
133
+ "-fopenmp",
134
+ "-lgomp",
135
+ "-flto",
136
+ "-fuse-linker-plugin"
137
+ ],
138
+ "xcode_settings": {
139
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
140
+ "GCC_ENABLE_CPP_RTTI": "YES",
141
+ "OTHER_CPLUSPLUSFLAGS": [
142
+ "-std=c++17",
143
+ "-O3",
144
+ "-ffast-math",
145
+ "-march=native",
146
+ "-funroll-loops"
147
+ ]
148
+ }
149
+ }]
150
+ ]
151
+ }
152
+ ]
153
+ }
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "rosepetal-image-engine",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "install": "node-gyp rebuild",
8
+ "build": "node-gyp build",
9
+ "configure": "node-gyp configure",
10
+ "rebuild": "node-gyp rebuild"
11
+ },
12
+ "gypfile": true,
13
+ "dependencies": {
14
+ "node-addon-api": "^7.1.0"
15
+ },
16
+ "devDependencies": {
17
+ "node-gyp": "^10.1.0"
18
+ }
19
+ }
@@ -0,0 +1,433 @@
1
+ #include <napi.h>
2
+ #include <opencv2/opencv.hpp>
3
+ #include "utils.h"
4
+ #include <unordered_map>
5
+ #include <vector>
6
+ #include <string>
7
+ #include <cmath>
8
+ #include <algorithm>
9
+ // OpenMP is only used through pragmas; omit the header to avoid requiring libomp headers on macOS.
10
+ // #include <omp.h>
11
+ // SSE2 header removed - was unused and breaks ARM builds (emmintrin.h is x86/x64 only)
12
+
13
+ // Structure for bounding box information
14
+ struct BBoxInfo {
15
+ cv::Rect boundingRect; // Pixel coordinates
16
+ std::string className;
17
+ float confidence;
18
+ cv::Scalar bgrColor; // Pre-computed BGR color (0-255)
19
+ std::string labelText; // Pre-computed label text
20
+ cv::Size textSize; // Cached text size
21
+ int baseline; // Cached baseline
22
+ };
23
+
24
+ // Color generation function for unmapped classes
25
+ inline cv::Vec3f GenerateMaximallyDifferentColor(
26
+ const std::string& className,
27
+ const std::unordered_map<std::string, cv::Vec3f>& userColors,
28
+ std::unordered_map<std::string, cv::Vec3f>& colorCache) {
29
+
30
+ // Collect all used colors
31
+ std::vector<cv::Vec3f> usedColors;
32
+ for (const auto& [_, color] : userColors) {
33
+ usedColors.push_back(color);
34
+ }
35
+ for (const auto& [_, color] : colorCache) {
36
+ usedColors.push_back(color);
37
+ }
38
+
39
+ // If no existing colors, start with a vivid red
40
+ if (usedColors.empty()) {
41
+ cv::Vec3f firstColor(0.0f, 0.0f, 1.0f); // BGR: pure red
42
+ colorCache[className] = firstColor;
43
+ return firstColor;
44
+ }
45
+
46
+ // Generate candidate colors evenly distributed in HSV space
47
+ std::vector<cv::Vec3f> candidates;
48
+ const int numHues = 24; // Every 15 degrees
49
+ const int numSaturations = 3; // 60%, 80%, 100%
50
+ const int numValues = 3; // 60%, 80%, 100%
51
+
52
+ for (int h = 0; h < numHues; h++) {
53
+ for (int s = 0; s < numSaturations; s++) {
54
+ for (int v = 0; v < numValues; v++) {
55
+ float hue = (h * 360.0f / numHues);
56
+ float saturation = 0.6f + s * 0.2f;
57
+ float value = 0.6f + v * 0.2f;
58
+
59
+ // Convert HSV to BGR
60
+ cv::Mat hsv(1, 1, CV_32FC3, cv::Scalar(hue / 360.0f, saturation, value));
61
+ cv::Mat bgr;
62
+ cv::cvtColor(hsv, bgr, cv::COLOR_HSV2BGR);
63
+
64
+ cv::Vec3f color = bgr.at<cv::Vec3f>(0, 0);
65
+ candidates.push_back(color);
66
+ }
67
+ }
68
+ }
69
+
70
+ // Find candidate with maximum minimum distance to existing colors
71
+ float maxMinDistance = 0;
72
+ cv::Vec3f bestColor = candidates[0];
73
+
74
+ for (const auto& candidate : candidates) {
75
+ float minDistance = std::numeric_limits<float>::max();
76
+
77
+ for (const auto& existing : usedColors) {
78
+ float dist = sqrt(
79
+ pow((candidate[2] - existing[2]) * 2.0f, 2) + // Red (BGR[2])
80
+ pow((candidate[1] - existing[1]) * 3.0f, 2) + // Green (BGR[1])
81
+ pow((candidate[0] - existing[0]) * 1.0f, 2) // Blue (BGR[0])
82
+ );
83
+ minDistance = std::min(minDistance, dist);
84
+ }
85
+
86
+ if (minDistance > maxMinDistance) {
87
+ maxMinDistance = minDistance;
88
+ bestColor = candidate;
89
+ }
90
+ }
91
+
92
+ colorCache[className] = bestColor;
93
+ return bestColor;
94
+ }
95
+
96
+ /*------------------------------------------------------------------------*/
97
+ class AddBBsWorker final : public Napi::AsyncWorker {
98
+ public:
99
+ AddBBsWorker(Napi::Function cb,
100
+ const Napi::Value& jsImg,
101
+ const Napi::Array& boxesArray,
102
+ const Napi::Object& classColorMap,
103
+ bool showClassName,
104
+ bool showConfidence,
105
+ bool onlyMapped,
106
+ int boxThickness,
107
+ double fontSize,
108
+ std::string fontPosition,
109
+ bool labelBackground,
110
+ std::string outputFormat,
111
+ int quality = 90,
112
+ bool pngOptimize = false)
113
+ : Napi::AsyncWorker(cb),
114
+ showClassName(showClassName),
115
+ showConfidence(showConfidence),
116
+ onlyMapped(onlyMapped),
117
+ boxThickness(boxThickness),
118
+ fontSize(fontSize),
119
+ fontPosition(std::move(fontPosition)),
120
+ labelBackground(labelBackground),
121
+ outputFormat(std::move(outputFormat)),
122
+ quality(quality),
123
+ pngOptimize(pngOptimize)
124
+ {
125
+ const int64 t0 = cv::getTickCount();
126
+
127
+ // Convert JavaScript image to OpenCV Mat
128
+ imageMat = ConvertToMat(jsImg);
129
+
130
+ // Parse class color map
131
+ std::unordered_map<std::string, cv::Vec3f> userColorMap;
132
+ Napi::Array colorMapKeys = classColorMap.GetPropertyNames();
133
+ for (size_t i = 0; i < colorMapKeys.Length(); i++) {
134
+ std::string className = colorMapKeys.Get(i).As<Napi::String>().Utf8Value();
135
+ std::string hexColor = classColorMap.Get(className).As<Napi::String>().Utf8Value();
136
+
137
+ if (hexColor.length() == 7 && hexColor[0] == '#') {
138
+ float r = std::stoi(hexColor.substr(1, 2), nullptr, 16) / 255.0f;
139
+ float g = std::stoi(hexColor.substr(3, 2), nullptr, 16) / 255.0f;
140
+ float b = std::stoi(hexColor.substr(5, 2), nullptr, 16) / 255.0f;
141
+ userColorMap[className] = cv::Vec3f(b, g, r); // BGR for OpenCV
142
+ // Debug: Print parsed color
143
+ // printf("Class %s: hex=%s -> BGR=(%.2f,%.2f,%.2f)\n", className.c_str(), hexColor.c_str(), b, g, r);
144
+ }
145
+ }
146
+
147
+ // Reserve capacity for better performance
148
+ bboxInfos.reserve(32); // Reserve for typical number of boxes
149
+
150
+ // Parse boxes array structure - direct array format
151
+ for (size_t boxIndex = 0; boxIndex < boxesArray.Length(); boxIndex++) {
152
+ Napi::Object boxObj = boxesArray.Get(boxIndex).As<Napi::Object>();
153
+
154
+ if (boxObj.Has("raw_boxes") && boxObj.Has("tag")) {
155
+ // Extract box coordinates (4 corners format)
156
+ Napi::Array box = boxObj.Get("raw_boxes").As<Napi::Array>();
157
+ if (box.Length() != 4) continue;
158
+
159
+ // Parse 4 corners: [[x1,y1], [x2,y1], [x2,y2], [x1,y2]]
160
+ std::vector<cv::Point2f> corners;
161
+ for (size_t i = 0; i < 4; i++) {
162
+ Napi::Array corner = box.Get(i).As<Napi::Array>();
163
+ if (corner.Length() >= 2) {
164
+ float x = corner.Get(0u).As<Napi::Number>().FloatValue();
165
+ float y = corner.Get(1u).As<Napi::Number>().FloatValue();
166
+ corners.emplace_back(x, y);
167
+ }
168
+ }
169
+
170
+ if (corners.size() != 4) continue;
171
+
172
+ // Extract tag (class name) and confidence
173
+ std::string className = boxObj.Get("tag").As<Napi::String>().Utf8Value();
174
+ float confidence = boxObj.Has("confidence") ?
175
+ boxObj.Get("confidence").As<Napi::Number>().FloatValue() : 1.0f;
176
+
177
+ // Skip unmapped classes if onlyMapped is true
178
+ if (onlyMapped) {
179
+ if (userColorMap.find(className) == userColorMap.end()) {
180
+ continue; // Skip this box
181
+ }
182
+ }
183
+
184
+ // Get color for this class and pre-compute BGR scalar
185
+ cv::Vec3f color;
186
+ auto colorIt = userColorMap.find(className);
187
+ if (colorIt != userColorMap.end()) {
188
+ color = colorIt->second;
189
+ } else {
190
+ color = GenerateMaximallyDifferentColor(className, userColorMap, colorCache);
191
+ }
192
+
193
+ // Pre-compute BGR color as Scalar for faster drawing
194
+ cv::Scalar bgrColor(
195
+ color[0] * 255.0f, // B
196
+ color[1] * 255.0f, // G
197
+ color[2] * 255.0f // R
198
+ );
199
+
200
+ // Convert normalized coordinates to pixels
201
+ cv::Rect bbox;
202
+ bbox.x = static_cast<int>(corners[0].x * imageMat.cols);
203
+ bbox.y = static_cast<int>(corners[0].y * imageMat.rows);
204
+ bbox.width = static_cast<int>((corners[2].x - corners[0].x) * imageMat.cols);
205
+ bbox.height = static_cast<int>((corners[2].y - corners[0].y) * imageMat.rows);
206
+
207
+ // Clamp to image bounds
208
+ bbox.x = std::max(0, std::min(imageMat.cols - 1, bbox.x));
209
+ bbox.y = std::max(0, std::min(imageMat.rows - 1, bbox.y));
210
+ bbox.width = std::min(bbox.width, imageMat.cols - bbox.x);
211
+ bbox.height = std::min(bbox.height, imageMat.rows - bbox.y);
212
+
213
+ // Pre-generate label text with optimized string handling
214
+ char labelBuffer[256];
215
+ if (showClassName && showConfidence) {
216
+ snprintf(labelBuffer, sizeof(labelBuffer), "%s (%.1f%%)", className.c_str(), confidence * 100.0f);
217
+ } else if (showClassName) {
218
+ snprintf(labelBuffer, sizeof(labelBuffer), "%s", className.c_str());
219
+ } else if (showConfidence) {
220
+ snprintf(labelBuffer, sizeof(labelBuffer), "%.1f%%", confidence * 100.0f);
221
+ } else {
222
+ labelBuffer[0] = '\0';
223
+ }
224
+ std::string labelText(labelBuffer);
225
+
226
+ // Store bbox info with pre-computed values
227
+ BBoxInfo info;
228
+ info.boundingRect = bbox;
229
+ info.className = className;
230
+ info.confidence = confidence;
231
+ info.bgrColor = bgrColor;
232
+ info.labelText = labelText;
233
+ bboxInfos.push_back(info);
234
+ }
235
+ }
236
+
237
+ imageFormat = DetectChannelFormatShared(jsImg, imageMat);
238
+ outputChannel = imageFormat;
239
+
240
+ convertMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
241
+ }
242
+
243
+ protected:
244
+ void Execute() override {
245
+ const int64 t0 = cv::getTickCount();
246
+
247
+ // Work directly on the image if possible, avoid clone
248
+ bool needsConversion = (imageFormat == "RGB" || imageFormat == "RGBA" || imageFormat == "GRAY");
249
+
250
+ if (needsConversion) {
251
+ // Convert and work on result directly
252
+ if (imageFormat == "RGB") {
253
+ cv::cvtColor(imageMat, result, cv::COLOR_RGB2BGR);
254
+ } else if (imageFormat == "RGBA") {
255
+ cv::cvtColor(imageMat, result, cv::COLOR_RGBA2BGR);
256
+ } else if (imageFormat == "GRAY") {
257
+ cv::cvtColor(imageMat, result, cv::COLOR_GRAY2BGR);
258
+ }
259
+ } else {
260
+ // Already BGR/BGRA - clone only if needed
261
+ result = imageMat.clone();
262
+ }
263
+
264
+ // Calculate scaling factor based on image dimensions
265
+ // Use geometric mean of dimensions, normalized to ~500px reference size
266
+ const double scaleFactor = std::sqrt(result.cols * result.rows) / 500.0;
267
+
268
+ // Scale box thickness and font size proportionally
269
+ const int actualBoxThickness = std::max(1, static_cast<int>(boxThickness * scaleFactor * 0.5));
270
+ // Font scale needs to be much larger for OpenCV (typically 0.5-2.0)
271
+ const double actualFontScale = fontSize * std::min(2.0, scaleFactor * 0.5);
272
+
273
+ // Font settings
274
+ const int fontFace = cv::FONT_HERSHEY_SIMPLEX;
275
+ const double fontScale = actualFontScale;
276
+ const int fontThickness = std::max(1, static_cast<int>(scaleFactor * 0.5));
277
+
278
+ // Pre-calculate text sizes for all boxes with optimized caching
279
+ std::unordered_map<std::string, std::pair<cv::Size, int>> textSizeCache;
280
+
281
+ // First pass: calculate unique text sizes
282
+ for (auto& bbox : bboxInfos) {
283
+ if (!bbox.labelText.empty() && textSizeCache.find(bbox.labelText) == textSizeCache.end()) {
284
+ int baseline = 0;
285
+ cv::Size size = cv::getTextSize(bbox.labelText, fontFace, fontScale, fontThickness, &baseline);
286
+ textSizeCache[bbox.labelText] = {size, baseline};
287
+ }
288
+ }
289
+
290
+ // Second pass: assign cached sizes
291
+ #pragma omp parallel for if(bboxInfos.size() > 20) schedule(static)
292
+ for (size_t i = 0; i < bboxInfos.size(); i++) {
293
+ auto& bbox = bboxInfos[i];
294
+ if (!bbox.labelText.empty()) {
295
+ const auto& cached = textSizeCache[bbox.labelText];
296
+ bbox.textSize = cached.first;
297
+ bbox.baseline = cached.second;
298
+ }
299
+ }
300
+
301
+ // Process each bounding box
302
+ for (const auto& bbox : bboxInfos) {
303
+ // Draw bounding box rectangle with faster LINE_4
304
+ cv::rectangle(result, bbox.boundingRect, bbox.bgrColor, actualBoxThickness, cv::LINE_4);
305
+
306
+ // Draw label if there's text
307
+ if (!bbox.labelText.empty()) {
308
+
309
+ // Pre-calculated positions
310
+ const int textX = bbox.boundingRect.x + 2;
311
+ const int textY = bbox.boundingRect.y - 3;
312
+
313
+ // Always draw background rectangle above the box (full opacity)
314
+ if (labelBackground) {
315
+ // Pre-calculate and clamp coordinates
316
+ const int bgX1 = std::max(0, bbox.boundingRect.x);
317
+ const int bgY1 = std::max(0, bbox.boundingRect.y - bbox.textSize.height - 6);
318
+ const int bgX2 = std::min(result.cols - 1, bbox.boundingRect.x + bbox.textSize.width + 4);
319
+ const int bgY2 = std::min(result.rows - 1, bbox.boundingRect.y - 1);
320
+
321
+ // Full opacity background with bbox color
322
+ cv::rectangle(result, cv::Point(bgX1, bgY1), cv::Point(bgX2, bgY2), bbox.bgrColor, cv::FILLED);
323
+ }
324
+
325
+ // Draw text with faster LINE_8 instead of LINE_AA
326
+ cv::Scalar textColor = labelBackground ? cv::Scalar(0, 0, 0) : bbox.bgrColor;
327
+ cv::putText(result, bbox.labelText, cv::Point(textX, textY), fontFace, fontScale, textColor, fontThickness, cv::LINE_8);
328
+ }
329
+ }
330
+
331
+ taskMs = (cv::getTickCount() - t0) / cv::getTickFrequency() * 1e3;
332
+
333
+ // Convert back to original format if needed
334
+ if (outputFormat == "raw") {
335
+ // Convert BGR result back to original format for raw output
336
+ if (imageFormat == "RGB") {
337
+ cv::cvtColor(result, result, cv::COLOR_BGR2RGB);
338
+ } else if (imageFormat == "RGBA") {
339
+ cv::cvtColor(result, result, cv::COLOR_BGR2RGBA);
340
+ } else if (imageFormat == "GRAY") {
341
+ cv::cvtColor(result, result, cv::COLOR_BGR2GRAY);
342
+ }
343
+ // If already BGR/BGRA, no conversion needed
344
+ } else {
345
+ // For encoded formats, keep as BGR
346
+ cv::Mat tmp = result;
347
+ encodeMs = EncodeToFormat(tmp, encodedBuf, outputFormat, quality, pngOptimize);
348
+ }
349
+ }
350
+
351
+ void OnOK() override {
352
+ Napi::Env env = Env();
353
+ Napi::Value jsImg = (outputFormat != "raw") ? VectorToBuffer(env, std::move(encodedBuf))
354
+ : MatToRawJS(env, result, outputChannel);
355
+
356
+ Napi::Object out = Napi::Object::New(env);
357
+ out.Set("image", jsImg);
358
+ out.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
359
+ out.Set("boxCount", Napi::Number::New(env, bboxInfos.size()));
360
+ Callback().Call({env.Null(), out});
361
+ }
362
+
363
+ private:
364
+ cv::Mat imageMat, result;
365
+ std::string imageFormat, outputChannel;
366
+ std::vector<BBoxInfo> bboxInfos;
367
+ bool showClassName, showConfidence, onlyMapped, labelBackground;
368
+ int boxThickness;
369
+ double fontSize;
370
+ std::string fontPosition;
371
+ std::string outputFormat;
372
+ int quality;
373
+ bool pngOptimize;
374
+ double convertMs = 0, taskMs = 0, encodeMs = 0;
375
+ std::vector<uchar> encodedBuf;
376
+ std::unordered_map<std::string, cv::Vec3f> colorCache; // Instance-based color cache
377
+ };
378
+
379
+ /*------------------------------------------------------------------------*/
380
+ Napi::Value AddBBs(const Napi::CallbackInfo& info) {
381
+ Napi::Env env = info.Env();
382
+
383
+ // Parameter validation
384
+ if (info.Length() < 12 || info.Length() > 15 || !info[info.Length() - 1].IsFunction()) {
385
+ Napi::TypeError::New(env, "addBBs(image, boxesArray, classColorMap, showClassName, showConfidence, onlyMapped, boxThickness, fontSize, fontPosition, labelBackground, [outputFormat], [quality], [pngOptimize], callback)")
386
+ .ThrowAsJavaScriptException();
387
+ return env.Null();
388
+ }
389
+
390
+ // Extract required parameters
391
+ Napi::Value jsImg = info[0];
392
+ Napi::Array boxesArray = info[1].As<Napi::Array>();
393
+ Napi::Object classColorMap = info[2].As<Napi::Object>();
394
+ bool showClassName = info[3].As<Napi::Boolean>().Value();
395
+ bool showConfidence = info[4].As<Napi::Boolean>().Value();
396
+ bool onlyMapped = info[5].As<Napi::Boolean>().Value();
397
+ int boxThickness = info[6].As<Napi::Number>().Int32Value();
398
+ double fontSize = info[7].As<Napi::Number>().DoubleValue();
399
+ std::string fontPosition = info[8].As<Napi::String>().Utf8Value();
400
+ bool labelBackground = info[9].As<Napi::Boolean>().Value();
401
+
402
+ // Handle optional parameters
403
+ std::string outputFormat = "raw";
404
+ int quality = 90;
405
+ bool pngOptimize = false;
406
+ size_t cbIdx = 10;
407
+
408
+ if (info.Length() >= 12) {
409
+ outputFormat = info[10].As<Napi::String>().Utf8Value();
410
+ cbIdx = 11;
411
+ }
412
+
413
+ if (info.Length() >= 13) {
414
+ quality = info[11].As<Napi::Number>().Int32Value();
415
+ cbIdx = 12;
416
+ }
417
+
418
+ if (info.Length() >= 14) {
419
+ pngOptimize = info[12].As<Napi::Boolean>().Value();
420
+ cbIdx = 13;
421
+ }
422
+
423
+ // Create and queue worker
424
+ (new AddBBsWorker(
425
+ info[cbIdx].As<Napi::Function>(),
426
+ jsImg, boxesArray, classColorMap,
427
+ showClassName, showConfidence, onlyMapped,
428
+ boxThickness, fontSize, fontPosition, labelBackground,
429
+ outputFormat, quality, pngOptimize
430
+ ))->Queue();
431
+
432
+ return env.Undefined();
433
+ }