@rosepetal/node-red-contrib-image-tools 1.5.5 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @file Pure-JS BMP decoder for uncompressed BI_RGB files (8/24/32-bit).
3
+ * Read-side counterpart of encodeBmpRaw in image-out; Sharp cannot read BMP.
4
+ * @author Rosepetal
5
+ */
6
+
7
+ function isBmp(buf) {
8
+ return Buffer.isBuffer(buf) && buf.length >= 2 && buf[0] === 0x42 && buf[1] === 0x4D;
9
+ }
10
+
11
+ // Decodes a BMP buffer to the toolkit's raw image object.
12
+ // Supports 8-bit palette, 24-bit and 32-bit uncompressed, top-down and bottom-up.
13
+ function decodeBmp(buf) {
14
+ if (!isBmp(buf) || buf.length < 54) throw new Error('Invalid BMP file');
15
+
16
+ const pixelOffset = buf.readUInt32LE(10);
17
+ const infoSize = buf.readUInt32LE(14);
18
+ if (infoSize < 40) throw new Error(`Unsupported BMP header (size ${infoSize})`);
19
+
20
+ const width = buf.readInt32LE(18);
21
+ const rawHeight = buf.readInt32LE(22);
22
+ const bpp = buf.readUInt16LE(28);
23
+ const compression = buf.readUInt32LE(30);
24
+
25
+ const topDown = rawHeight < 0;
26
+ const height = Math.abs(rawHeight);
27
+ if (width <= 0 || height === 0) throw new Error('Invalid BMP dimensions');
28
+ if (compression !== 0) throw new Error(`Unsupported BMP compression ${compression} (only uncompressed BI_RGB)`);
29
+ if (bpp !== 8 && bpp !== 24 && bpp !== 32) throw new Error(`Unsupported BMP bit depth ${bpp} (only 8/24/32)`);
30
+
31
+ const srcStride = (width * (bpp / 8) + 3) & ~3;
32
+ if (pixelOffset + srcStride * height > buf.length) throw new Error('Corrupt BMP: pixel data truncated');
33
+
34
+ // 8-bit files carry a BGRA palette; an all-gray palette maps to a GRAY image
35
+ let palette = null;
36
+ let grayPalette = false;
37
+ if (bpp === 8) {
38
+ const colors = buf.readUInt32LE(46) || 256;
39
+ const palOffset = 14 + infoSize;
40
+ if (palOffset + colors * 4 > buf.length) throw new Error('Corrupt BMP: palette truncated');
41
+ palette = [];
42
+ grayPalette = true;
43
+ for (let i = 0; i < colors; i++) {
44
+ const b = buf[palOffset + i * 4], g = buf[palOffset + i * 4 + 1], r = buf[palOffset + i * 4 + 2];
45
+ if (r !== g || g !== b) grayPalette = false;
46
+ palette.push([r, g, b]);
47
+ }
48
+ }
49
+
50
+ const channels = bpp === 32 ? 4 : (bpp === 24 || !grayPalette) ? 3 : 1;
51
+ const colorSpace = channels === 4 ? 'RGBA' : channels === 3 ? 'RGB' : 'GRAY';
52
+ const out = Buffer.alloc(width * height * channels);
53
+
54
+ for (let y = 0; y < height; y++) {
55
+ const srcRow = pixelOffset + (topDown ? y : height - 1 - y) * srcStride;
56
+ const dstRow = y * width * channels;
57
+ if (bpp === 8) {
58
+ for (let x = 0; x < width; x++) {
59
+ const entry = palette[buf[srcRow + x]] || [0, 0, 0];
60
+ if (channels === 1) {
61
+ out[dstRow + x] = entry[0];
62
+ } else {
63
+ const d = dstRow + x * 3;
64
+ out[d] = entry[0]; out[d + 1] = entry[1]; out[d + 2] = entry[2];
65
+ }
66
+ }
67
+ } else {
68
+ for (let x = 0; x < width; x++) {
69
+ const s = srcRow + x * (bpp / 8), d = dstRow + x * channels;
70
+ out[d] = buf[s + 2]; out[d + 1] = buf[s + 1]; out[d + 2] = buf[s]; // BGR → RGB
71
+ if (channels === 4) out[d + 3] = buf[s + 3];
72
+ }
73
+ }
74
+ }
75
+
76
+ return { data: out, width, height, channels, colorSpace, dtype: 'uint8' };
77
+ }
78
+
79
+ module.exports = { isBmp, decodeBmp };
@@ -14,6 +14,7 @@ try {
14
14
  }
15
15
  const fs = require('fs').promises;
16
16
  const path = require('path');
17
+ const BmpDecode = require('../../lib/bmp-decode.js');
17
18
 
18
19
  module.exports = function(RED) {
19
20
  const NodeUtils = require('../../lib/node-utils.js')(RED);
@@ -103,13 +104,16 @@ module.exports = function(RED) {
103
104
  // Read encoded file once so we can reuse it for both decoding and debug preview
104
105
  const fileBuffer = await fs.readFile(filePath);
105
106
 
106
- // Use Sharp to decode image with full metadata
107
- const sharpInstance = sharp(fileBuffer);
107
+ // Decode: BMP natively (Sharp cannot read it), everything else via Sharp
108
108
  const decodeStart = performance.now();
109
- const { data, info } = await sharpInstance
110
- .clone()
111
- .raw()
112
- .toBuffer({ resolveWithObject: true });
109
+ let data, info;
110
+ if (BmpDecode.isBmp(fileBuffer)) {
111
+ const decoded = BmpDecode.decodeBmp(fileBuffer);
112
+ data = decoded.data;
113
+ info = { width: decoded.width, height: decoded.height, channels: decoded.channels };
114
+ } else {
115
+ ({ data, info } = await sharp(fileBuffer).raw().toBuffer({ resolveWithObject: true }));
116
+ }
113
117
  const decodeMs = performance.now() - decodeStart;
114
118
 
115
119
  // Determine colorSpace from Sharp info
@@ -11,6 +11,7 @@ try {
11
11
  sharp = null;
12
12
  }
13
13
  const fs = require('fs').promises;
14
+ const BmpDecode = require('../../lib/bmp-decode.js');
14
15
 
15
16
  module.exports = function(RED) {
16
17
  const NodeUtils = require('../../lib/node-utils.js')(RED);
@@ -46,10 +47,16 @@ module.exports = function(RED) {
46
47
  return;
47
48
  }
48
49
 
49
- // Use Sharp to decode image with full metadata
50
- const { data, info } = await sharp(filePath)
51
- .raw()
52
- .toBuffer({ resolveWithObject: true });
50
+ // Decode: BMP natively (Sharp cannot read it), everything else via Sharp
51
+ const fileBuffer = await fs.readFile(filePath);
52
+ let data, info;
53
+ if (BmpDecode.isBmp(fileBuffer)) {
54
+ const decoded = BmpDecode.decodeBmp(fileBuffer);
55
+ data = decoded.data;
56
+ info = { width: decoded.width, height: decoded.height, channels: decoded.channels };
57
+ } else {
58
+ ({ data, info } = await sharp(fileBuffer).raw().toBuffer({ resolveWithObject: true }));
59
+ }
53
60
 
54
61
  // Determine colorSpace from Sharp info
55
62
  let colorSpace;
@@ -20,8 +20,10 @@
20
20
  debugWidth:{value:200},
21
21
  debugWidthType:{value:"num"},
22
22
  colormap:{value:"JET"},
23
- blurSize:{value:0},
24
- threshold:{value:0}
23
+ blurSize:{value:0}, blurSizeType:{value:"num"},
24
+ threshold:{value:0}, thresholdType:{value:"num"},
25
+ statsEnabled:{value:true},
26
+ statsPath:{value:"diffStats"}, statsPathType:{value:"msg"}
25
27
  },
26
28
  inputs:1,outputs:1,
27
29
  label:function(){return this.name||"rp-heat-diff";},
@@ -35,15 +37,24 @@
35
37
  $("#node-input-outputPath").typedInput({
36
38
  default:'msg',types:['msg','flow','global'],
37
39
  typeField:"#node-input-outputPathType"});
40
+ $("#node-input-statsPath").typedInput({
41
+ default:'msg',types:['msg','flow','global'],
42
+ typeField:"#node-input-statsPathType"});
38
43
 
39
- // Threshold slider
40
- var $thresholdSlider = $("#node-input-threshold");
41
- var $thresholdValue = $("#threshold-value");
42
- function updateThresholdDisplay() {
43
- $thresholdValue.text($thresholdSlider.val());
44
+ // Stats path only relevant when stats are enabled
45
+ var statsCheckbox = $('#node-input-statsEnabled');
46
+ function updateStatsPathVisibility(){
47
+ $("#stats-path-row").toggle(statsCheckbox.is(':checked'));
44
48
  }
45
- $thresholdSlider.on("input", updateThresholdDisplay);
46
- updateThresholdDisplay();
49
+ statsCheckbox.on('change', updateStatsPathVisibility);
50
+ updateStatsPathVisibility();
51
+
52
+ $("#node-input-blurSize").typedInput({
53
+ default:'num',types:['num','msg','flow','global'],
54
+ typeField:"#node-input-blurSizeType"});
55
+ $("#node-input-threshold").typedInput({
56
+ default:'num',types:['num','msg','flow','global'],
57
+ typeField:"#node-input-thresholdType"});
47
58
 
48
59
  // Output format visibility
49
60
  function updateQualityVisibility(){
@@ -109,6 +120,17 @@
109
120
  </select>
110
121
  </div>
111
122
 
123
+ <div class="form-row">
124
+ <label for="node-input-statsEnabled"><i class="fa fa-bar-chart"></i> Statistics</label>
125
+ <input type="checkbox" id="node-input-statsEnabled" style="display:inline-block; width:auto; vertical-align:baseline;">
126
+ <label for="node-input-statsEnabled" style="width:auto; margin-left:5px;">Compute diff statistics</label>
127
+ </div>
128
+ <div class="form-row" id="stats-path-row">
129
+ <label for="node-input-statsPath"><i class="fa fa-bar-chart"></i> Stats to</label>
130
+ <input type="text" id="node-input-statsPath" style="width:70%;">
131
+ <input type="hidden" id="node-input-statsPathType">
132
+ </div>
133
+
112
134
  <div class="form-row" id="quality-row">
113
135
  <label for="node-input-outputQuality"><i class="fa fa-sliders"></i> Quality</label>
114
136
  <input type="number" id="node-input-outputQuality" min="1" max="100" value="90" style="width: 70px;">
@@ -169,17 +191,16 @@
169
191
 
170
192
  <div class="form-row">
171
193
  <label for="node-input-blurSize"><i class="fa fa-circle-o"></i> Blur</label>
172
- <input type="number" id="node-input-blurSize" min="0" max="99" value="0" style="width: 70px;">
194
+ <input type="text" id="node-input-blurSize" style="width: 160px;">
195
+ <input type="hidden" id="node-input-blurSizeType">
173
196
  <span style="margin-left: 10px; color: #666;">Gaussian blur kernel size (0 = off, odd values)</span>
174
197
  </div>
175
198
 
176
199
  <div class="form-row">
177
200
  <label for="node-input-threshold"><i class="fa fa-filter"></i> Threshold</label>
178
- <input type="range" id="node-input-threshold" min="0" max="255" value="0" style="width: 200px;">
179
- <span id="threshold-value" style="margin-left: 10px; font-weight: bold;">0</span>
180
- <div style="margin-top: 5px; font-size: 10px; color: #999;">
181
- Pixel differences below this value are suppressed (0 = show all)
182
- </div>
201
+ <input type="text" id="node-input-threshold" style="width: 160px;">
202
+ <input type="hidden" id="node-input-thresholdType">
203
+ <span style="margin-left: 10px; color: #666;">0-255; differences below this are suppressed (0 = show all)</span>
183
204
  </div>
184
205
  </script>
185
206
 
@@ -203,11 +224,17 @@
203
224
  <dt>Colormap <span class="property-type">string</span></dt>
204
225
  <dd>Color mapping applied to the difference: JET, HOT, INFERNO, TURBO, BONE, COOL, RAINBOW, OCEAN, PINK, HSV.</dd>
205
226
 
206
- <dt>Blur <span class="property-type">number</span></dt>
207
- <dd>Gaussian blur kernel size applied to the difference before colormapping. Smooths noise. 0 to disable.</dd>
227
+ <dt>Blur <span class="property-type">number | msg | flow | global</span></dt>
228
+ <dd>Gaussian blur kernel size applied to the difference before colormapping. Smooths noise. 0 to disable. Can be a fixed number or resolved from a msg/flow/global property per message.</dd>
229
+
230
+ <dt>Threshold <span class="property-type">number | msg | flow | global</span></dt>
231
+ <dd>Pixel differences below this value (0-255) are set to zero before colormapping. Suppresses minor noise. Also defines which pixels count as "changed" for the statistics. Can be a fixed number or resolved from a msg/flow/global property per message.</dd>
232
+
233
+ <dt>Statistics <span class="property-type">boolean</span></dt>
234
+ <dd>When enabled (default), numeric diff statistics are computed.</dd>
208
235
 
209
- <dt>Threshold <span class="property-type">number</span></dt>
210
- <dd>Pixel differences below this value (0-255) are set to zero before colormapping. Suppresses minor noise.</dd>
236
+ <dt>Stats to <span class="property-type">string</span></dt>
237
+ <dd>Message property where the statistics object is stored. Default <code>msg.diffStats</code>.</dd>
211
238
  </dl>
212
239
 
213
240
  <h3>Inputs</h3>
@@ -215,4 +242,17 @@
215
242
 
216
243
  <h3>Outputs</h3>
217
244
  <p>A 3-channel BGR heat map image in the selected output format. If the inputs were arrays, the output is an array of heat maps in the same order.</p>
245
+ <p>When Statistics is enabled, the configured stats property (default <code>msg.diffStats</code>) holds an object (or array, matching the input shape) with:</p>
246
+ <dl class="message-properties">
247
+ <dt>validRatio <span class="property-type">number</span></dt>
248
+ <dd>Fraction of pixels used for statistics. Pixels that are pure black in either input (alignment borders, composite padding) are excluded from all stats.</dd>
249
+ <dt>changedRatio <span class="property-type">number</span></dt>
250
+ <dd>Fraction of valid pixels whose difference exceeds the threshold.</dd>
251
+ <dt>meanDiff / maxDiff / p50 / p95 / p99 <span class="property-type">number</span></dt>
252
+ <dd>Mean, maximum and percentiles of the difference values (0-255) over valid pixels.</dd>
253
+ <dt>rmse / psnr / ssim <span class="property-type">number</span></dt>
254
+ <dd>Root-mean-square error, peak signal-to-noise ratio (dB, 100 = identical) and structural similarity (0-1, 1 = identical).</dd>
255
+ <dt>blobCount / largestBlobArea / blobs <span class="property-type">number | array</span></dt>
256
+ <dd>Connected regions of changed pixels. <code>blobs</code> lists up to 50 regions, largest first, each with <code>x, y, w, h, area, cx, cy</code> in output-image coordinates.</dd>
257
+ </dl>
218
258
  </script>
@@ -132,11 +132,17 @@ module.exports = function (RED) {
132
132
  /* Options from the editor */
133
133
  const colormapName = config.colormap || 'JET';
134
134
  const colormapType = COLORMAP[colormapName] !== undefined ? COLORMAP[colormapName] : 2;
135
- const blurSize = Math.max(0, parseInt(config.blurSize) || 0);
136
- const threshold = Math.max(0, Math.min(255, parseInt(config.threshold) || 0));
135
+ const blurSize = Math.max(0, parseInt(NodeUtils.resolveDimension(
136
+ node, config.blurSizeType || 'num', config.blurSize, msg)) || 0);
137
+ const threshold = Math.max(0, Math.min(255, parseInt(NodeUtils.resolveDimension(
138
+ node, config.thresholdType || 'num', config.threshold, msg)) || 0));
137
139
  const outputFormat = config.outputFormat || 'raw';
138
140
  const outputQuality = parseInt(config.outputQuality) || 90;
139
141
  const pngOptimize = config.pngOptimize || false;
142
+ // Stats on by default; existing flows without the property get them too
143
+ const statsEnabled = config.statsEnabled !== false && config.statsEnabled !== 'false';
144
+ const statsPath = config.statsPath || 'diffStats';
145
+ const statsPathType = config.statsPathType || 'msg';
140
146
  const useSharpWebp = outputFormat === 'webp' && NodeUtils.hasAdvancedWebpOptions(config);
141
147
  const cppFormat = useSharpWebp ? 'raw' : outputFormat;
142
148
 
@@ -144,7 +150,7 @@ module.exports = function (RED) {
144
150
  const results = await Promise.all(
145
151
  list1.map((img1, i) =>
146
152
  Cpp.heatDiff(img1, list2[i], colormapType, blurSize, threshold,
147
- cppFormat, outputQuality, pngOptimize))
153
+ cppFormat, outputQuality, pngOptimize, statsEnabled))
148
154
  );
149
155
 
150
156
  // Aggregate timings across pairs
@@ -168,6 +174,12 @@ module.exports = function (RED) {
168
174
  /* Write result — array in, array out */
169
175
  RED.util.setMessageProperty(msg, outputPath, isArray ? images : images[0]);
170
176
 
177
+ /* Diff statistics, same shape as the image output */
178
+ if (statsEnabled) {
179
+ const stats = results.map(r => r.stats);
180
+ NodeUtils.setOutputValue(node, msg, statsPath, statsPathType, isArray ? stats : stats[0]);
181
+ }
182
+
171
183
  /* Status */
172
184
  const total = performance.now() - t0;
173
185
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-darwin-arm64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt native binary for macOS ARM64 (Apple Silicon)",
5
5
  "os": ["darwin"],
6
6
  "cpu": ["arm64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-darwin-x64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt native binary for macOS x64 (Intel)",
5
5
  "os": ["darwin"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linux-arm64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt native binary for Linux ARM64 (glibc)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["arm64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linux-x64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt native binary for Linux x64 (glibc)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt native binary for Linux x64 (musl/Alpine)",
5
5
  "os": ["linux"],
6
6
  "cpu": ["x64"],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/rosepetal-engine-win32-x64",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Prebuilt rosepetal-image-engine binary for Windows x64",
5
5
  "os": ["win32"],
6
6
  "cpu": ["x64"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools",
3
- "version": "1.5.5",
3
+ "version": "1.6.1",
4
4
  "description": "Node-RED Image Processing Toolkit",
5
5
  "main": "install.sh",
6
6
  "directories": {
@@ -36,11 +36,11 @@
36
36
  "sharp": "^0.34.2"
37
37
  },
38
38
  "optionalDependencies": {
39
- "@rosepetal/node-red-contrib-image-tools-linux-x64": "1.5.5",
40
- "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.5.5",
41
- "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.5.5",
42
- "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.5.5",
43
- "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.5.5"
39
+ "@rosepetal/node-red-contrib-image-tools-linux-x64": "1.6.1",
40
+ "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.6.1",
41
+ "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.6.1",
42
+ "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.6.1",
43
+ "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.6.1"
44
44
  },
45
45
  "node-red": {
46
46
  "version": ">=1.0.0",
@@ -1,7 +1,31 @@
1
1
  #include <napi.h>
2
2
  #include <opencv2/opencv.hpp>
3
+ #include <algorithm>
4
+ #include <cmath>
3
5
  #include "utils.h"
4
6
 
7
+ // Mean SSIM over the valid mask (standard 11x11 Gaussian, sigma 1.5)
8
+ static double MaskedSSIM(const cv::Mat& img1, const cv::Mat& img2, const cv::Mat& valid) {
9
+ const double C1 = 6.5025, C2 = 58.5225;
10
+ cv::Mat a, b;
11
+ img1.convertTo(a, CV_32F);
12
+ img2.convertTo(b, CV_32F);
13
+ const cv::Size k(11, 11);
14
+ cv::Mat mu1, mu2;
15
+ cv::GaussianBlur(a, mu1, k, 1.5);
16
+ cv::GaussianBlur(b, mu2, k, 1.5);
17
+ cv::Mat mu1sq = mu1.mul(mu1), mu2sq = mu2.mul(mu2), mu12 = mu1.mul(mu2);
18
+ cv::Mat s1, s2, s12;
19
+ cv::GaussianBlur(a.mul(a), s1, k, 1.5); s1 -= mu1sq;
20
+ cv::GaussianBlur(b.mul(b), s2, k, 1.5); s2 -= mu2sq;
21
+ cv::GaussianBlur(a.mul(b), s12, k, 1.5); s12 -= mu12;
22
+ cv::Mat num = (2 * mu12 + C1).mul(2 * s12 + C2);
23
+ cv::Mat den = (mu1sq + mu2sq + C1).mul(s1 + s2 + C2);
24
+ cv::Mat map;
25
+ cv::divide(num, den, map);
26
+ return cv::mean(map, valid)[0];
27
+ }
28
+
5
29
  class HeatDiffWorker final : public Napi::AsyncWorker {
6
30
  public:
7
31
  HeatDiffWorker(Napi::Function cb,
@@ -12,14 +36,16 @@ public:
12
36
  int threshold,
13
37
  std::string outputFormat,
14
38
  int quality = 90,
15
- bool pngOptimize = false)
39
+ bool pngOptimize = false,
40
+ bool computeStats = false)
16
41
  : Napi::AsyncWorker(cb),
17
42
  colormapType(colormapType),
18
43
  blurSize(blurSize),
19
44
  threshold(threshold),
20
45
  outputFormat(std::move(outputFormat)),
21
46
  quality(quality),
22
- pngOptimize(pngOptimize)
47
+ pngOptimize(pngOptimize),
48
+ computeStats(computeStats)
23
49
  {
24
50
  const int64 t0 = cv::getTickCount();
25
51
  mat1 = ConvertToMat(jsImg1);
@@ -75,6 +101,8 @@ protected:
75
101
  cv::threshold(diff, diff, threshold, 0, cv::THRESH_TOZERO);
76
102
  }
77
103
 
104
+ if (computeStats) ComputeStats(diff, gray1, gray2);
105
+
78
106
  // Apply colormap
79
107
  cv::applyColorMap(diff, result, colormapType);
80
108
  // applyColorMap outputs BGR
@@ -97,10 +125,107 @@ protected:
97
125
  Napi::Object out = Napi::Object::New(env);
98
126
  out.Set("image", jsImg);
99
127
  out.Set("timing", MakeTimingJS(env, convertMs, taskMs, encodeMs));
128
+
129
+ if (computeStats) {
130
+ Napi::Object st = Napi::Object::New(env);
131
+ st.Set("validRatio", statValidRatio);
132
+ st.Set("changedRatio", statChangedRatio);
133
+ st.Set("meanDiff", statMean);
134
+ st.Set("maxDiff", statMax);
135
+ st.Set("p50", statP50);
136
+ st.Set("p95", statP95);
137
+ st.Set("p99", statP99);
138
+ st.Set("rmse", statRmse);
139
+ st.Set("psnr", statPsnr);
140
+ st.Set("ssim", statSsim);
141
+ st.Set("threshold", threshold);
142
+ st.Set("blobCount", statBlobCount);
143
+ st.Set("largestBlobArea", statLargestBlobArea);
144
+ Napi::Array arr = Napi::Array::New(env, statBlobs.size());
145
+ for (size_t i = 0; i < statBlobs.size(); i++) {
146
+ const BlobStat& b = statBlobs[i];
147
+ Napi::Object o = Napi::Object::New(env);
148
+ o.Set("x", b.x); o.Set("y", b.y); o.Set("w", b.w); o.Set("h", b.h);
149
+ o.Set("area", b.area);
150
+ o.Set("cx", b.cx); o.Set("cy", b.cy);
151
+ arr.Set(static_cast<uint32_t>(i), o);
152
+ }
153
+ st.Set("blobs", arr);
154
+ out.Set("stats", st);
155
+ }
156
+
100
157
  Callback().Call({env.Null(), out});
101
158
  }
102
159
 
103
160
  private:
161
+ struct BlobStat { int x, y, w, h, area; double cx, cy; };
162
+ static constexpr size_t kMaxBlobs = 50;
163
+
164
+ // All stats ignore pixels that are pure black in either input (alignment
165
+ // borders / composite padding produce huge fake diffs there).
166
+ void ComputeStats(const cv::Mat& diff, const cv::Mat& gray1, const cv::Mat& gray2) {
167
+ const double total = static_cast<double>(diff.rows) * diff.cols;
168
+ cv::Mat valid = (gray1 > 0) & (gray2 > 0);
169
+ const int validCount = cv::countNonZero(valid);
170
+ statValidRatio = validCount / total;
171
+ if (validCount == 0) return;
172
+
173
+ cv::Mat changed;
174
+ cv::compare(diff, threshold, changed, cv::CMP_GT);
175
+ changed &= valid;
176
+ statChangedRatio = cv::countNonZero(changed) / static_cast<double>(validCount);
177
+
178
+ statMean = cv::mean(diff, valid)[0];
179
+ double maxVal = 0;
180
+ cv::minMaxLoc(diff, nullptr, &maxVal, nullptr, nullptr, valid);
181
+ statMax = maxVal;
182
+
183
+ // Percentiles of the diff values via a masked 256-bin histogram
184
+ int histSize = 256;
185
+ float range[] = {0, 256};
186
+ const float* ranges[] = {range};
187
+ cv::Mat hist;
188
+ cv::calcHist(&diff, 1, nullptr, valid, hist, 1, &histSize, ranges);
189
+ double cum = 0;
190
+ statP50 = statP95 = statP99 = -1;
191
+ for (int i = 0; i < histSize; i++) {
192
+ cum += hist.at<float>(i);
193
+ const double frac = cum / validCount;
194
+ if (statP50 < 0 && frac >= 0.50) statP50 = i;
195
+ if (statP95 < 0 && frac >= 0.95) statP95 = i;
196
+ if (statP99 < 0 && frac >= 0.99) { statP99 = i; break; }
197
+ }
198
+
199
+ cv::Mat diffF;
200
+ diff.convertTo(diffF, CV_32F);
201
+ const double meanSq = cv::mean(diffF.mul(diffF), valid)[0];
202
+ statRmse = std::sqrt(meanSq);
203
+ statPsnr = meanSq > 0 ? 10.0 * std::log10(255.0 * 255.0 / meanSq) : 100.0;
204
+
205
+ statSsim = MaskedSSIM(gray1, gray2, valid);
206
+
207
+ // Connected components on the changed mask -> blobs (largest first, capped)
208
+ cv::Mat labels, ccStats, centroids;
209
+ const int n = cv::connectedComponentsWithStats(changed, labels, ccStats, centroids, 8, CV_32S);
210
+ statBlobCount = n - 1;
211
+ std::vector<BlobStat> blobs;
212
+ blobs.reserve(n - 1);
213
+ for (int i = 1; i < n; i++) {
214
+ blobs.push_back({ccStats.at<int>(i, cv::CC_STAT_LEFT),
215
+ ccStats.at<int>(i, cv::CC_STAT_TOP),
216
+ ccStats.at<int>(i, cv::CC_STAT_WIDTH),
217
+ ccStats.at<int>(i, cv::CC_STAT_HEIGHT),
218
+ ccStats.at<int>(i, cv::CC_STAT_AREA),
219
+ centroids.at<double>(i, 0),
220
+ centroids.at<double>(i, 1)});
221
+ }
222
+ std::sort(blobs.begin(), blobs.end(),
223
+ [](const BlobStat& a, const BlobStat& b) { return a.area > b.area; });
224
+ if (blobs.size() > kMaxBlobs) blobs.resize(kMaxBlobs);
225
+ statLargestBlobArea = blobs.empty() ? 0 : blobs[0].area;
226
+ statBlobs = std::move(blobs);
227
+ }
228
+
104
229
  cv::Mat mat1, mat2, result;
105
230
  std::string format1, format2, outputChannel;
106
231
  int colormapType;
@@ -109,8 +234,14 @@ private:
109
234
  std::string outputFormat;
110
235
  int quality;
111
236
  bool pngOptimize;
237
+ bool computeStats;
112
238
  double convertMs = 0, taskMs = 0, encodeMs = 0;
113
239
  std::vector<uchar> encodedBuf;
240
+
241
+ double statValidRatio = 0, statChangedRatio = 0, statMean = 0, statMax = 0;
242
+ double statP50 = 0, statP95 = 0, statP99 = 0, statRmse = 0, statPsnr = 0, statSsim = 0;
243
+ int statBlobCount = 0, statLargestBlobArea = 0;
244
+ std::vector<BlobStat> statBlobs;
114
245
  };
115
246
 
116
247
  Napi::Value HeatDiff(const Napi::CallbackInfo& info) {
@@ -118,7 +249,7 @@ Napi::Value HeatDiff(const Napi::CallbackInfo& info) {
118
249
 
119
250
  if (info.Length() < 3 || !info[info.Length() - 1].IsFunction()) {
120
251
  Napi::TypeError::New(env,
121
- "heatDiff(image1, image2, colormapType, [blurSize], [threshold], [outputFormat], [quality], [pngOptimize], callback)")
252
+ "heatDiff(image1, image2, colormapType, [blurSize], [threshold], [outputFormat], [quality], [pngOptimize], [computeStats], callback)")
122
253
  .ThrowAsJavaScriptException();
123
254
  return env.Null();
124
255
  }
@@ -132,15 +263,18 @@ Napi::Value HeatDiff(const Napi::CallbackInfo& info) {
132
263
  std::string outputFormat = "raw";
133
264
  int quality = 90;
134
265
  bool pngOptimize = false;
266
+ bool computeStats = false;
135
267
  size_t cbIdx = 3;
136
268
 
137
- if (info.Length() >= 5) { blurSize = info[3].As<Napi::Number>().Int32Value(); cbIdx = 4; }
138
- if (info.Length() >= 6) { threshold = info[4].As<Napi::Number>().Int32Value(); cbIdx = 5; }
139
- if (info.Length() >= 7) { outputFormat = info[5].As<Napi::String>().Utf8Value(); cbIdx = 6; }
140
- if (info.Length() >= 8) { quality = info[6].As<Napi::Number>().Int32Value(); cbIdx = 7; }
141
- if (info.Length() >= 9) { pngOptimize = info[7].As<Napi::Boolean>().Value(); cbIdx = 8; }
269
+ if (info.Length() >= 5) { blurSize = info[3].As<Napi::Number>().Int32Value(); cbIdx = 4; }
270
+ if (info.Length() >= 6) { threshold = info[4].As<Napi::Number>().Int32Value(); cbIdx = 5; }
271
+ if (info.Length() >= 7) { outputFormat = info[5].As<Napi::String>().Utf8Value(); cbIdx = 6; }
272
+ if (info.Length() >= 8) { quality = info[6].As<Napi::Number>().Int32Value(); cbIdx = 7; }
273
+ if (info.Length() >= 9) { pngOptimize = info[7].As<Napi::Boolean>().Value(); cbIdx = 8; }
274
+ if (info.Length() >= 10) { computeStats = info[8].As<Napi::Boolean>().Value(); cbIdx = 9; }
142
275
 
143
276
  (new HeatDiffWorker(info[cbIdx].As<Napi::Function>(),
144
- jsImg1, jsImg2, colormapType, blurSize, threshold, outputFormat, quality, pngOptimize))->Queue();
277
+ jsImg1, jsImg2, colormapType, blurSize, threshold, outputFormat, quality, pngOptimize,
278
+ computeStats))->Queue();
145
279
  return env.Undefined();
146
280
  }