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

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.
@@ -211,8 +211,8 @@
211
211
  </dl>
212
212
 
213
213
  <h3>Inputs</h3>
214
- <p>Two images in the standard format (raw image object or encoded buffer). Images of different sizes are resized to match the larger one.</p>
214
+ <p>Two images in the standard format (raw image object or encoded buffer), or two arrays of images of the same length — images are paired by index and one heat map is produced per pair. Mixing a single image with an array, or arrays of different lengths, raises an error. Images of different sizes are resized to match the larger one.</p>
215
215
 
216
216
  <h3>Outputs</h3>
217
- <p>A 3-channel BGR heat map image in the selected output format.</p>
217
+ <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>
218
218
  </script>
@@ -2,6 +2,7 @@
2
2
  * Node-RED logic for *rosepetal-heat-diff* (C++ backend).
3
3
  * Computes absolute difference between two images and applies a colormap
4
4
  * to produce a heat map visualization of the differences.
5
+ * Accepts two single images or two same-length arrays (paired by index).
5
6
  *
6
7
  * Timing fields returned by C++:
7
8
  * timing.convertMs . timing.taskMs . timing.encodeMs
@@ -67,35 +68,64 @@ module.exports = function (RED) {
67
68
  details: { image1Path, image2Path, outputPath }
68
69
  },
69
70
  msg, send, done,
70
- { originalPayload: baseImageForPassthrough, outputPath, outputType: 'single' }
71
+ { originalPayload: baseImageForPassthrough, outputPath, outputType: 'preserve' }
71
72
  );
72
73
  }
73
74
 
74
- const img1 = NodeUtils.validateImageStructure(image1, node);
75
- if (!img1) {
75
+ // Both inputs must have the same shape: two singles, or two same-length arrays
76
+ const isArray = Array.isArray(image1);
77
+ if (isArray !== Array.isArray(image2)) {
76
78
  return NodeUtils.handleValidationErrorWithPassthrough(
77
79
  node,
78
80
  {
79
- message: 'First image is invalid or missing',
80
- hint: `Check that "${image1Path}" contains a valid image.`,
81
+ message: 'image1 and image2 must both be single images or both be arrays',
82
+ hint: `"${image1Path}" is ${isArray ? 'an array' : 'a single image'} but "${image2Path}" is not.`,
81
83
  details: { image1Path, image2Path, outputPath }
82
84
  },
83
85
  msg, send, done,
84
- { originalPayload: baseImageForPassthrough, outputPath, outputType: 'single' }
86
+ { originalPayload: baseImageForPassthrough, outputPath, outputType: 'preserve' }
87
+ );
88
+ }
89
+ if (isArray && (image1.length === 0 || image1.length !== image2.length)) {
90
+ return NodeUtils.handleValidationErrorWithPassthrough(
91
+ node,
92
+ {
93
+ message: `Image arrays must be non-empty and of equal length (got ${image1.length} and ${image2.length})`,
94
+ hint: 'Images are paired by index; both arrays must contain the same number of images.',
95
+ details: { image1Path, image2Path, outputPath }
96
+ },
97
+ msg, send, done,
98
+ { originalPayload: baseImageForPassthrough, outputPath, outputType: 'preserve' }
99
+ );
100
+ }
101
+
102
+ const list1 = (isArray ? image1 : [image1])
103
+ .map(img => NodeUtils.validateImageStructure(img, node));
104
+ if (list1.some(img => !img)) {
105
+ return NodeUtils.handleValidationErrorWithPassthrough(
106
+ node,
107
+ {
108
+ message: 'First image input is invalid or missing',
109
+ hint: `Check that "${image1Path}" contains valid image(s).`,
110
+ details: { image1Path, image2Path, outputPath }
111
+ },
112
+ msg, send, done,
113
+ { originalPayload: baseImageForPassthrough, outputPath, outputType: 'preserve' }
85
114
  );
86
115
  }
87
116
 
88
- const img2 = NodeUtils.validateImageStructure(image2, node);
89
- if (!img2) {
117
+ const list2 = (isArray ? image2 : [image2])
118
+ .map(img => NodeUtils.validateImageStructure(img, node));
119
+ if (list2.some(img => !img)) {
90
120
  return NodeUtils.handleValidationErrorWithPassthrough(
91
121
  node,
92
122
  {
93
- message: 'Second image is invalid or missing',
94
- hint: `Check that "${image2Path}" contains a valid image.`,
123
+ message: 'Second image input is invalid or missing',
124
+ hint: `Check that "${image2Path}" contains valid image(s).`,
95
125
  details: { image1Path, image2Path, outputPath }
96
126
  },
97
127
  msg, send, done,
98
- { originalPayload: baseImageForPassthrough, outputPath, outputType: 'single' }
128
+ { originalPayload: baseImageForPassthrough, outputPath, outputType: 'preserve' }
99
129
  );
100
130
  }
101
131
 
@@ -110,17 +140,33 @@ module.exports = function (RED) {
110
140
  const useSharpWebp = outputFormat === 'webp' && NodeUtils.hasAdvancedWebpOptions(config);
111
141
  const cppFormat = useSharpWebp ? 'raw' : outputFormat;
112
142
 
113
- /* Single call to the C++ addon */
114
- let { image, timing = {} } =
115
- await Cpp.heatDiff(img1, img2, colormapType, blurSize, threshold,
116
- cppFormat, outputQuality, pngOptimize);
143
+ /* One C++ call per pair (index-matched) */
144
+ const results = await Promise.all(
145
+ list1.map((img1, i) =>
146
+ Cpp.heatDiff(img1, list2[i], colormapType, blurSize, threshold,
147
+ cppFormat, outputQuality, pngOptimize))
148
+ );
149
+
150
+ // Aggregate timings across pairs
151
+ const timing = results.reduce(
152
+ (acc, { timing: t }) => {
153
+ acc.convertMs += t?.convertMs ?? 0;
154
+ acc.taskMs += t?.taskMs ?? 0;
155
+ acc.encodeMs += t?.encodeMs ?? 0;
156
+ return acc;
157
+ },
158
+ { convertMs: 0, taskMs: 0, encodeMs: 0 }
159
+ );
160
+ const images = results.map(r => r.image);
117
161
 
118
162
  if (useSharpWebp) {
119
- image = await NodeUtils.encodeWebpAdvanced(image, config);
163
+ for (let i = 0; i < images.length; i++) {
164
+ images[i] = await NodeUtils.encodeWebpAdvanced(images[i], config);
165
+ }
120
166
  }
121
167
 
122
- /* Write result */
123
- RED.util.setMessageProperty(msg, outputPath, image);
168
+ /* Write result — array in, array out */
169
+ RED.util.setMessageProperty(msg, outputPath, isArray ? images : images[0]);
124
170
 
125
171
  /* Status */
126
172
  const total = performance.now() - t0;
@@ -137,14 +183,16 @@ module.exports = function (RED) {
137
183
  );
138
184
  debugWidth = Math.max(1, parseInt(debugWidth) || 200);
139
185
 
186
+ // For arrays, show the first heat map as representative
140
187
  const debugResult = await NodeUtils.debugImageDisplay(
141
- image, outputFormat, outputQuality,
188
+ images[0], outputFormat, outputQuality,
142
189
  node, debugEnabled, debugWidth
143
190
  );
144
191
 
145
192
  if (debugResult) {
146
193
  debugFormat = debugResult.formatMessage;
147
- NodeUtils.setSuccessStatusWithDebug(node, 1, total, timing, debugFormat);
194
+ NodeUtils.setSuccessStatusWithDebug(node, results.length, total, timing,
195
+ debugFormat + (isArray ? ' (first)' : ''));
148
196
  }
149
197
  } catch (debugError) {
150
198
  node.warn(`Debug display error: ${debugError.message}`);
@@ -152,10 +200,10 @@ module.exports = function (RED) {
152
200
  }
153
201
 
154
202
  if (!debugFormat) {
155
- NodeUtils.setSuccessStatus(node, 1, total, timing);
203
+ NodeUtils.setSuccessStatus(node, results.length, total, timing);
156
204
  }
157
205
 
158
- NodeUtils.recordPerformanceMetrics(node, msg, timing || {}, total);
206
+ NodeUtils.recordPerformanceMetrics(node, msg, timing, total);
159
207
 
160
208
  send(msg);
161
209
  done && done();
@@ -165,7 +213,7 @@ module.exports = function (RED) {
165
213
  {
166
214
  originalPayload: baseImageForPassthrough,
167
215
  outputPath,
168
- outputType: 'single',
216
+ outputType: 'preserve',
169
217
  context: { image1Path, image2Path, outputPath }
170
218
  }
171
219
  );
@@ -43,6 +43,11 @@
43
43
  // never - never run ECC (equivalent to pipeline=features)
44
44
  // Default 'always' for back-compat. Existing saved flows use 'always'.
45
45
  eccRefine: { value: "always" },
46
+ // Feature detector for the seed stage (features / features+ecc):
47
+ // orb - binary descriptors, fastest (default)
48
+ // sift - float descriptors, more robust on low-texture/blurry
49
+ // images, ~2-4x slower
50
+ detector: { value: "orb" },
46
51
  returnMatrix: { value: false },
47
52
  transformPolygon: { value: false },
48
53
  polygonPath: { value: "payload.polygon" },
@@ -217,11 +222,32 @@
217
222
  // ECC Refine policy is only meaningful when ECC actually runs
218
223
  $('#ecc-refine-row').toggle(pipeline === 'features+ecc');
219
224
  $('#ecc-refine-description').toggle(pipeline === 'features+ecc');
225
+ // Detector is only used by the feature-seed stage
226
+ $('#detector-row').toggle(pipeline !== 'ecc');
227
+ $('#detector-description').toggle(pipeline !== 'ecc');
220
228
  }
221
229
 
222
230
  $('#node-input-pipeline').on('change', updatePipelineDescription);
223
231
  updatePipelineDescription();
224
232
 
233
+ // Detector description
234
+ function updateDetectorDescription() {
235
+ const detector = $('#node-input-detector').val();
236
+ let description = '';
237
+ switch (detector) {
238
+ case 'orb':
239
+ description = 'ORB: binary descriptors, fastest. Good default for textured industrial images.';
240
+ break;
241
+ case 'sift':
242
+ description = 'SIFT: float descriptors, more robust on low-texture, blurry, or scale-changed images. ~2-4x slower than ORB.';
243
+ break;
244
+ }
245
+ $('#detector-description').text(description);
246
+ }
247
+
248
+ $('#node-input-detector').on('change', updateDetectorDescription);
249
+ updateDetectorDescription();
250
+
225
251
  // ECC Refine description
226
252
  function updateEccRefineDescription() {
227
253
  const eccRefine = $('#node-input-eccRefine').val();
@@ -491,6 +517,18 @@
491
517
  <div id="pipeline-description" style="font-size: 12px; color: #666; margin-top: 5px;"></div>
492
518
  </div>
493
519
 
520
+ <div class="form-row" id="detector-row">
521
+ <label for="node-input-detector"><i class="fa fa-dot-circle-o"></i> Detector</label>
522
+ <select id="node-input-detector" style="width: 250px;">
523
+ <option value="orb">ORB (fast, default)</option>
524
+ <option value="sift">SIFT (robust, slower)</option>
525
+ </select>
526
+ </div>
527
+ <div class="form-row">
528
+ <label></label>
529
+ <div id="detector-description" style="font-size: 12px; color: #666; margin-top: 5px;"></div>
530
+ </div>
531
+
494
532
  <div class="form-row" id="ecc-refine-row">
495
533
  <label for="node-input-eccRefine"><i class="fa fa-rocket"></i> ECC Refine</label>
496
534
  <select id="node-input-eccRefine" style="width: 250px;">
@@ -670,6 +708,18 @@
670
708
  <div id="pipeline-description" style="font-size: 12px; color: #666; margin-top: 5px;"></div>
671
709
  </div>
672
710
 
711
+ <div class="form-row" id="detector-row">
712
+ <label for="node-input-detector"><i class="fa fa-dot-circle-o"></i> Detector</label>
713
+ <select id="node-input-detector" style="width: 250px;">
714
+ <option value="orb">ORB (fast, default)</option>
715
+ <option value="sift">SIFT (robust, slower)</option>
716
+ </select>
717
+ </div>
718
+ <div class="form-row">
719
+ <label></label>
720
+ <div id="detector-description" style="font-size: 12px; color: #666; margin-top: 5px;"></div>
721
+ </div>
722
+
673
723
  <div class="form-row" id="ecc-refine-row">
674
724
  <label for="node-input-eccRefine"><i class="fa fa-rocket"></i> ECC Refine</label>
675
725
  <select id="node-input-eccRefine" style="width: 250px;">
@@ -768,6 +818,14 @@
768
818
  </ul>
769
819
  New nodes default to <code>features+ecc</code>; existing saved flows that lack this field fall back to <code>ecc</code> for full backward compatibility. If ECC diverges after a successful feature seed, the seed itself is returned (rather than failing the alignment).
770
820
  </dd>
821
+ <dt>Detector <span class="property-type">string</span></dt>
822
+ <dd>Feature detector used by the seed stage (pipelines <code>features</code> and <code>features+ecc</code>):
823
+ <ul>
824
+ <li><code>orb</code> &mdash; binary descriptors, fastest. Good default for textured industrial images. Legacy behavior.</li>
825
+ <li><code>sift</code> &mdash; float descriptors, more robust on low-texture, blurry, or scale-changed images; roughly 2-4x slower than ORB.</li>
826
+ </ul>
827
+ Ignored when Pipeline is <code>ecc</code>. Default <code>orb</code>.
828
+ </dd>
771
829
  <dt>ECC Refine <span class="property-type">string</span></dt>
772
830
  <dd>Only used when Pipeline is <code>features+ecc</code>. Controls whether ECC's slow iterative refinement actually runs after the ORB seed:
773
831
  <ul>
@@ -805,6 +863,7 @@
805
863
  <li><code>preset</code>: speed preset used</li>
806
864
  <li><code>pipeline</code>: pipeline used (<code>ecc</code>, <code>features</code>, or <code>features+ecc</code>)</li>
807
865
  <li><code>eccRefine</code>: ECC refinement policy used (<code>always</code>, <code>auto</code>, or <code>never</code>)</li>
866
+ <li><code>detector</code>: feature detector used (<code>orb</code> or <code>sift</code>)</li>
808
867
  <li><code>motionModel</code>: motion model used (<code>translation</code>, <code>euclidean</code>, <code>affine</code>, or <code>homography</code>)</li>
809
868
  <li><code>transformMatrix</code>: (optional) transformation matrix when enabled:
810
869
  <ul>
@@ -914,6 +973,14 @@ msg.payload = targetImageObject;</code></pre>
914
973
  </ul>
915
974
  New nodes default to <code>features+ecc</code>; existing saved flows that lack this field fall back to <code>ecc</code> for full backward compatibility. If ECC diverges after a successful feature seed, the seed itself is returned (rather than failing the alignment).
916
975
  </dd>
976
+ <dt>Detector <span class="property-type">string</span></dt>
977
+ <dd>Feature detector used by the seed stage (pipelines <code>features</code> and <code>features+ecc</code>):
978
+ <ul>
979
+ <li><code>orb</code> &mdash; binary descriptors, fastest. Good default for textured industrial images. Legacy behavior.</li>
980
+ <li><code>sift</code> &mdash; float descriptors, more robust on low-texture, blurry, or scale-changed images; roughly 2-4x slower than ORB.</li>
981
+ </ul>
982
+ Ignored when Pipeline is <code>ecc</code>. Default <code>orb</code>.
983
+ </dd>
917
984
  <dt>ECC Refine <span class="property-type">string</span></dt>
918
985
  <dd>Only used when Pipeline is <code>features+ecc</code>. Controls whether ECC's slow iterative refinement actually runs after the ORB seed:
919
986
  <ul>
@@ -951,6 +1018,7 @@ msg.payload = targetImageObject;</code></pre>
951
1018
  <li><code>preset</code>: speed preset used</li>
952
1019
  <li><code>pipeline</code>: pipeline used (<code>ecc</code>, <code>features</code>, or <code>features+ecc</code>)</li>
953
1020
  <li><code>eccRefine</code>: ECC refinement policy used (<code>always</code>, <code>auto</code>, or <code>never</code>)</li>
1021
+ <li><code>detector</code>: feature detector used (<code>orb</code> or <code>sift</code>)</li>
954
1022
  <li><code>motionModel</code>: motion model used (<code>translation</code>, <code>euclidean</code>, <code>affine</code>, or <code>homography</code>)</li>
955
1023
  <li><code>transformMatrix</code>: (optional) transformation matrix when enabled:
956
1024
  <ul>
@@ -132,6 +132,24 @@ module.exports = function (RED) {
132
132
  );
133
133
  }
134
134
 
135
+ // Feature detector for the seed stage (pipelines features / features+ecc).
136
+ // orb - binary descriptors, fastest (default)
137
+ // sift - float descriptors, more robust on low-texture/blurry images
138
+ const detector = config.detector || 'orb';
139
+ const VALID_DETECTORS = ['orb', 'sift'];
140
+ if (!VALID_DETECTORS.includes(detector)) {
141
+ return NodeUtils.handleValidationErrorWithPassthrough(
142
+ node,
143
+ {
144
+ message: `Invalid detector "${detector}"`,
145
+ hint: `detector must be one of: ${VALID_DETECTORS.join(', ')}`,
146
+ details: { detector, referenceImagePath, targetImagePath, outputPath }
147
+ },
148
+ msg, send, done,
149
+ { originalPayload: passthroughImage, outputPath, outputType: 'single' }
150
+ );
151
+ }
152
+
135
153
  /* ▸ Read images from message ------------------------------------ */
136
154
  // Validate input images
137
155
  const ref = NodeUtils.validateImageStructure(referenceImage, node);
@@ -322,7 +340,8 @@ module.exports = function (RED) {
322
340
  polygon,
323
341
  motionModel,
324
342
  pipeline,
325
- eccRefine
343
+ eccRefine,
344
+ detector
326
345
  );
327
346
 
328
347
  if (useSharpWebp) {
@@ -382,7 +401,8 @@ module.exports = function (RED) {
382
401
  preset: preset,
383
402
  motionModel: motionModel,
384
403
  pipeline: pipeline,
385
- eccRefine: eccRefine
404
+ eccRefine: eccRefine,
405
+ detector: detector
386
406
  };
387
407
 
388
408
  // Add transformation matrix if returned
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rosepetal/node-red-contrib-image-tools-darwin-arm64",
3
- "version": "1.5.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
3
+ "version": "1.5.5",
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.3",
40
- "@rosepetal/node-red-contrib-image-tools-linux-arm64": "1.5.3",
41
- "@rosepetal/node-red-contrib-image-tools-linuxmusl-x64": "1.5.3",
42
- "@rosepetal/node-red-contrib-image-tools-darwin-x64": "1.5.3",
43
- "@rosepetal/node-red-contrib-image-tools-darwin-arm64": "1.5.3"
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"
44
44
  },
45
45
  "node-red": {
46
46
  "version": ">=1.0.0",
@@ -185,6 +185,18 @@ static EccRefineMode ParseEccRefine(const std::string& name) {
185
185
  " (expected: always, auto, or never)");
186
186
  }
187
187
 
188
+ // Feature detector for the feature-seed stage:
189
+ // ORB - binary descriptors, fastest (default)
190
+ // SIFT - float descriptors, more robust on low-texture/blurry images, slower
191
+ enum class FeatureDetectorKind { ORB, SIFT };
192
+
193
+ static FeatureDetectorKind ParseDetector(const std::string& name) {
194
+ if (name == "orb") return FeatureDetectorKind::ORB;
195
+ if (name == "sift") return FeatureDetectorKind::SIFT;
196
+ throw std::runtime_error("Unknown detector: " + name +
197
+ " (expected: orb or sift)");
198
+ }
199
+
188
200
  class ImageAlignWorker : public Napi::AsyncWorker {
189
201
  public:
190
202
  ImageAlignWorker(Napi::Function& callback,
@@ -200,7 +212,8 @@ public:
200
212
  const Napi::Value& polygonValue = Napi::Value(),
201
213
  std::string motionModel = "translation",
202
214
  std::string pipeline = "ecc",
203
- std::string eccRefine = "always")
215
+ std::string eccRefine = "always",
216
+ std::string detector = "orb")
204
217
  : Napi::AsyncWorker(callback),
205
218
  scale(scale),
206
219
  maxIterations(maxIterations),
@@ -216,6 +229,8 @@ public:
216
229
  pipelineMode(AlignPipeline::ECC),
217
230
  eccRefineName(std::move(eccRefine)),
218
231
  eccRefineMode(EccRefineMode::ALWAYS),
232
+ detectorName(std::move(detector)),
233
+ detectorKind(FeatureDetectorKind::ORB),
219
234
  alignmentSuccess(false),
220
235
  hasPolygon(false),
221
236
  isPolygonArray(false) {
@@ -234,6 +249,9 @@ public:
234
249
  // And the ECC refinement policy (always / auto / never).
235
250
  eccRefineMode = ParseEccRefine(eccRefineName);
236
251
 
252
+ // And the feature detector (orb / sift).
253
+ detectorKind = ParseDetector(detectorName);
254
+
237
255
  // Convert input images to OpenCV Mat
238
256
  referenceMat = ConvertToMat(referenceImage);
239
257
  targetMat = ConvertToMat(targetImage);
@@ -328,11 +346,19 @@ protected:
328
346
  int refHeight = referenceMat.rows;
329
347
  int refWidth = referenceMat.cols;
330
348
 
349
+ // Only ECC (pixel-for-pixel correlation) and the polygon round-trip
350
+ // (normalizes by reference dims) require equal sizes. The features
351
+ // pipeline works on keypoint coordinates, and forcing the resize
352
+ // there injects an anisotropic stretch the motion model can only
353
+ // "explain" as a spurious rotation.
354
+ const bool needsSameSize =
355
+ (pipelineMode != AlignPipeline::FEATURES) || hasPolygon;
356
+
331
357
  // Resize target image to match reference dimensions, with caching.
332
358
  // For the constant-golden / changing-scan production pattern, the
333
359
  // golden's resize result is constant per call. Hash + cache it.
334
360
  cv::Mat targetResized;
335
- if (targetMat.size() != referenceMat.size()) {
361
+ if (needsSameSize && targetMat.size() != referenceMat.size()) {
336
362
  const uint64_t key = FastImageFingerprint(targetMat)
337
363
  ^ (static_cast<uint64_t>(refWidth) << 16)
338
364
  ^ static_cast<uint64_t>(refHeight)
@@ -381,6 +407,10 @@ protected:
381
407
 
382
408
  // Apply transformation to the color target image
383
409
  ApplyTransformation(targetResized, transformMatrix, cv::Size(refWidth, refHeight));
410
+ } else if (targetResized.size() != referenceMat.size()) {
411
+ // Alignment failed with the resize skipped: still emit a
412
+ // reference-sized image to keep the output-dimension contract.
413
+ cv::resize(targetResized, alignedImage, cv::Size(refWidth, refHeight));
384
414
  } else {
385
415
  // If alignment fails, use the resized target as-is
386
416
  alignedImage = targetResized;
@@ -545,6 +575,10 @@ private:
545
575
  std::string eccRefineName; // raw string from JS ('always' | 'auto' | 'never')
546
576
  EccRefineMode eccRefineMode; // resolved enum
547
577
 
578
+ // Feature detector for the seed stage ('orb' | 'sift')
579
+ std::string detectorName;
580
+ FeatureDetectorKind detectorKind;
581
+
548
582
  bool alignmentSuccess;
549
583
 
550
584
  // Polygon data
@@ -622,9 +656,13 @@ private:
622
656
  try {
623
657
  // First check the seed-matrix cache: if we've already solved this
624
658
  // exact (ref, target, motion) triple, return the saved matrix and
625
- // skip everything (ORB detect/describe, BFMatcher, RANSAC).
626
- const uint64_t refFp = FastImageFingerprint(refGray);
627
- const uint64_t targetFp = FastImageFingerprint(targetGray);
659
+ // skip everything (detect/describe, BFMatcher, RANSAC).
660
+ // Fingerprints are salted with the detector kind so ORB and SIFT
661
+ // entries (features and seed matrices) never collide.
662
+ const uint64_t detSalt = (detectorKind == FeatureDetectorKind::SIFT)
663
+ ? 0x51465400d5a7c3b1ULL : 0ULL;
664
+ const uint64_t refFp = FastImageFingerprint(refGray) ^ detSalt;
665
+ const uint64_t targetFp = FastImageFingerprint(targetGray) ^ detSalt;
628
666
  // Composite key: mix the two fingerprints with the motion flag.
629
667
  uint64_t seedKey = refFp;
630
668
  seedKey ^= targetFp + 0x9e3779b97f4a7c15ULL + (seedKey << 6) + (seedKey >> 2);
@@ -643,15 +681,20 @@ private:
643
681
  }
644
682
  }
645
683
 
646
- cv::Ptr<cv::ORB> orb = cv::ORB::create(
647
- /*nfeatures*/ 800,
648
- /*scaleFactor*/ 1.2f,
649
- /*nlevels*/ 5);
684
+ cv::Ptr<cv::Feature2D> det;
685
+ if (detectorKind == FeatureDetectorKind::SIFT) {
686
+ det = cv::SIFT::create(/*nfeatures*/ 800);
687
+ } else {
688
+ det = cv::ORB::create(
689
+ /*nfeatures*/ 800,
690
+ /*scaleFactor*/ 1.2f,
691
+ /*nlevels*/ 5);
692
+ }
650
693
 
651
694
  // Detect-or-cache helper. Looks up by FastImageFingerprint and skips
652
- // ORB entirely on cache hit. The big win is the "constant golden,
695
+ // detection entirely on cache hit. The big win is the "constant golden,
653
696
  // changing scan" pattern: golden hits the cache from call #2 onward.
654
- auto detectOrCached = [&orb](const cv::Mat& img, uint64_t fp,
697
+ auto detectOrCached = [&det](const cv::Mat& img, uint64_t fp,
655
698
  std::vector<cv::KeyPoint>& kp,
656
699
  cv::Mat& des) {
657
700
  OrbCacheEntry hit;
@@ -660,7 +703,7 @@ private:
660
703
  des = hit.des;
661
704
  return;
662
705
  }
663
- orb->detectAndCompute(img, cv::noArray(), kp, des);
706
+ det->detectAndCompute(img, cv::noArray(), kp, des);
664
707
  OrbCacheEntry e;
665
708
  e.kp = kp;
666
709
  e.des = des.clone(); // detach storage
@@ -687,8 +730,11 @@ private:
687
730
  return false;
688
731
  }
689
732
 
690
- // Brute-force Hamming + Lowe's ratio test (0.75) for robust matching.
691
- cv::BFMatcher matcher(cv::NORM_HAMMING, /*crossCheck=*/false);
733
+ // Brute-force matching + Lowe's ratio test (0.75).
734
+ // Hamming for ORB's binary descriptors, L2 for SIFT's floats.
735
+ const int normType = (detectorKind == FeatureDetectorKind::SIFT)
736
+ ? cv::NORM_L2 : cv::NORM_HAMMING;
737
+ cv::BFMatcher matcher(normType, /*crossCheck=*/false);
692
738
  std::vector<std::vector<cv::DMatch>> knn;
693
739
  matcher.knnMatch(des1, des2, knn, 2);
694
740
 
@@ -728,9 +774,12 @@ private:
728
774
 
729
775
  // Translation and Euclidean both start from a partial-affine estimate
730
776
  // (translation + rotation + uniform scale = 4 DoF), then post-process
731
- // it to drop the unwanted DoFs.
777
+ // it to drop the unwanted DoFs. Classic RANSAC here, not USAC:
778
+ // estimateAffinePartial2D rejects every USAC_* method (throws
779
+ // StsBadArg on all OpenCV versions), which made these seeds
780
+ // silently fail forever.
732
781
  cv::Mat P = cv::estimateAffinePartial2D(srcPts, dstPts, inlierMask,
733
- cv::USAC_MAGSAC, 5.0);
782
+ cv::RANSAC, 5.0);
734
783
  if (P.empty()) return false;
735
784
  P.convertTo(P, CV_32F);
736
785
 
@@ -804,21 +853,21 @@ private:
804
853
  // instead of returning a wildly wrong identity warp.
805
854
  bool FindTransformation(const cv::Mat& refGray, const cv::Mat& targetGray, cv::Mat& transformMatrix) {
806
855
  try {
807
- int height = refGray.rows;
808
- int width = refGray.cols;
809
-
810
856
  // Downsample images for faster alignment.
811
- // ORB and ECC both run on this same small grid so all intermediate
812
- // matrix arithmetic stays in small-frame coords; we rescale once at
813
- // the very end via RescaleSmallToFull().
814
- int scaledWidth = std::max(1, static_cast<int>(std::round(width * scale)));
815
- int scaledHeight = std::max(1, static_cast<int>(std::round(height * scale)));
816
-
857
+ // Each image is scaled by the same *factor* (not to the ref's dims:
858
+ // sizes can legitimately differ on the features pipeline, and forcing
859
+ // ref dims onto the target would stretch it anisotropically).
860
+ // RescaleSmallToFull divides translation by exactly `scale`, so both
861
+ // sides must use that factor. Equal-sized inputs get identical dims,
862
+ // keeping the common path bit-identical.
863
+ //
817
864
  // Cached resize: skips cv::resize when the input gray hasn't changed
818
865
  // (constant-golden, repeated-call pattern). Lookup is keyed by the
819
866
  // FULL-resolution input fingerprint AND the requested small dims.
820
- auto resizeOrCached = [scaledWidth, scaledHeight](const cv::Mat& fullGray,
821
- cv::Mat& smallOut) {
867
+ auto resizeOrCached = [this](const cv::Mat& fullGray,
868
+ cv::Mat& smallOut) {
869
+ const int scaledWidth = std::max(1, static_cast<int>(std::round(fullGray.cols * scale)));
870
+ const int scaledHeight = std::max(1, static_cast<int>(std::round(fullGray.rows * scale)));
822
871
  const uint64_t key = FastImageFingerprint(fullGray)
823
872
  ^ (static_cast<uint64_t>(scaledWidth) << 16)
824
873
  ^ static_cast<uint64_t>(scaledHeight);
@@ -1069,8 +1118,8 @@ Napi::Value ImageAlign(const Napi::CallbackInfo& info) {
1069
1118
  Napi::Env env = info.Env();
1070
1119
 
1071
1120
  // Validate arguments - expect callback as last argument
1072
- if (info.Length() < 3 || info.Length() > 14 || !info[info.Length() - 1].IsFunction()) {
1073
- Napi::TypeError::New(env, "imageAlign(referenceImage, targetImage, [scale], [maxIterations], [terminationEps], [outputFormat], [quality], [pngOptimize], [returnMatrix], [polygon], [motionModel], [pipeline], [eccRefine], callback)")
1121
+ if (info.Length() < 3 || info.Length() > 15 || !info[info.Length() - 1].IsFunction()) {
1122
+ Napi::TypeError::New(env, "imageAlign(referenceImage, targetImage, [scale], [maxIterations], [terminationEps], [outputFormat], [quality], [pngOptimize], [returnMatrix], [polygon], [motionModel], [pipeline], [eccRefine], [detector], callback)")
1074
1123
  .ThrowAsJavaScriptException();
1075
1124
  return env.Null();
1076
1125
  }
@@ -1096,6 +1145,8 @@ Napi::Value ImageAlign(const Napi::CallbackInfo& info) {
1096
1145
  std::string pipeline = "ecc";
1097
1146
  // Default eccRefine is "always" - never silently skips ECC.
1098
1147
  std::string eccRefine = "always";
1148
+ // Default detector is ORB (fastest; pre-existing behavior).
1149
+ std::string detector = "orb";
1099
1150
 
1100
1151
  // Parse optional parameters (before callback)
1101
1152
  if (info.Length() >= 4) {
@@ -1131,12 +1182,15 @@ Napi::Value ImageAlign(const Napi::CallbackInfo& info) {
1131
1182
  if (info.Length() >= 14) {
1132
1183
  eccRefine = info[12].As<Napi::String>().Utf8Value();
1133
1184
  }
1185
+ if (info.Length() >= 15) {
1186
+ detector = info[13].As<Napi::String>().Utf8Value();
1187
+ }
1134
1188
 
1135
1189
  // Create and queue worker
1136
1190
  ImageAlignWorker* worker = new ImageAlignWorker(callback, referenceImage, targetImage,
1137
1191
  scale, maxIterations, terminationEps,
1138
1192
  outputFormat, quality, pngOptimize, returnMatrix, polygon,
1139
- motionModel, pipeline, eccRefine);
1193
+ motionModel, pipeline, eccRefine, detector);
1140
1194
  worker->Queue();
1141
1195
 
1142
1196
  return env.Undefined();