@rosepetal/node-red-contrib-image-tools 1.4.3 → 1.5.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.
- package/artifacts/darwin-arm64/package.json +1 -1
- package/artifacts/linux-arm64/package.json +1 -1
- package/artifacts/linux-x64/package.json +1 -1
- package/artifacts/linuxmusl-x64/package.json +1 -1
- package/node-red-contrib-image-tools/nodes/io/image-out.html +19 -0
- package/node-red-contrib-image-tools/nodes/io/image-out.js +8 -4
- package/node-red-contrib-image-tools/nodes/specialized/heat-diff.html +218 -0
- package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +177 -0
- package/node-red-contrib-image-tools/nodes/specialized/image-align.html +243 -16
- package/node-red-contrib-image-tools/nodes/specialized/image-align.js +71 -2
- package/node-red-contrib-image-tools/nodes/transform/filter.html +111 -2
- package/node-red-contrib-image-tools/nodes/transform/filter.js +15 -4
- package/npm/darwin-arm64/package.json +1 -1
- package/npm/darwin-x64/package.json +1 -1
- package/npm/linux-arm64/package.json +1 -1
- package/npm/linux-x64/package.json +1 -1
- package/npm/linuxmusl-x64/package.json +1 -1
- package/npm/win32-x64/package.json +1 -1
- package/package.json +8 -7
- package/rosepetal-image-engine/binding.gyp +29 -3
- package/rosepetal-image-engine/src/filter.cpp +144 -0
- package/rosepetal-image-engine/src/heat-diff.cpp +146 -0
- package/rosepetal-image-engine/src/image-align.cpp +708 -116
- package/rosepetal-image-engine/src/main.cpp +2 -0
- package/scripts/build-opencv-static.ps1 +7 -2
- package/scripts/build-opencv-static.sh +13 -2
|
@@ -10,8 +10,181 @@
|
|
|
10
10
|
#include <cmath>
|
|
11
11
|
#include <algorithm>
|
|
12
12
|
#include <utility>
|
|
13
|
+
#include <mutex>
|
|
14
|
+
#include <list>
|
|
15
|
+
#include <unordered_map>
|
|
16
|
+
#include <cstdint>
|
|
17
|
+
#include <future>
|
|
13
18
|
#include "utils.h"
|
|
14
19
|
|
|
20
|
+
// ----------------------------------------------------------------------------
|
|
21
|
+
// ORB feature cache (process-wide, thread-safe LRU).
|
|
22
|
+
//
|
|
23
|
+
// In the typical "one golden, many scans" inspection pattern, the golden's ORB
|
|
24
|
+
// features are recomputed every call even though they never change. This
|
|
25
|
+
// cache fingerprints the small downsampled grayscale image (cheap FNV-1a over
|
|
26
|
+
// dims + first/last 256 bytes) and reuses keypoints+descriptors across calls.
|
|
27
|
+
// In tight loops on the same input pair, both ref and target hit the cache.
|
|
28
|
+
// ----------------------------------------------------------------------------
|
|
29
|
+
namespace {
|
|
30
|
+
|
|
31
|
+
inline uint64_t FastImageFingerprint(const cv::Mat& img) {
|
|
32
|
+
uint64_t h = 0xcbf29ce484222325ULL;
|
|
33
|
+
auto mix8 = [&](uint8_t b) { h ^= b; h *= 0x100000001b3ULL; };
|
|
34
|
+
mix8(static_cast<uint8_t>(img.cols & 0xff));
|
|
35
|
+
mix8(static_cast<uint8_t>((img.cols >> 8) & 0xff));
|
|
36
|
+
mix8(static_cast<uint8_t>((img.cols >> 16) & 0xff));
|
|
37
|
+
mix8(static_cast<uint8_t>(img.rows & 0xff));
|
|
38
|
+
mix8(static_cast<uint8_t>((img.rows >> 8) & 0xff));
|
|
39
|
+
mix8(static_cast<uint8_t>((img.rows >> 16) & 0xff));
|
|
40
|
+
mix8(static_cast<uint8_t>(img.channels()));
|
|
41
|
+
if (img.empty() || !img.isContinuous()) {
|
|
42
|
+
return h;
|
|
43
|
+
}
|
|
44
|
+
const uint8_t* data = img.ptr<uint8_t>();
|
|
45
|
+
const size_t totalBytes = img.total() * img.elemSize();
|
|
46
|
+
const size_t step = std::min<size_t>(256, totalBytes);
|
|
47
|
+
for (size_t i = 0; i < step; i++) mix8(data[i]);
|
|
48
|
+
if (totalBytes > 2 * step) {
|
|
49
|
+
for (size_t i = totalBytes - step; i < totalBytes; i++) mix8(data[i]);
|
|
50
|
+
}
|
|
51
|
+
if (totalBytes > 4 * step) {
|
|
52
|
+
const size_t mid = totalBytes / 2;
|
|
53
|
+
for (size_t i = mid; i < mid + step; i++) mix8(data[i]);
|
|
54
|
+
}
|
|
55
|
+
return h;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
struct OrbCacheEntry {
|
|
59
|
+
std::vector<cv::KeyPoint> kp;
|
|
60
|
+
cv::Mat des; // owned (cloned) so the cv::Mat header is independent
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// ECC-prepared float32 image: normalized to zero mean / unit variance.
|
|
64
|
+
// Cached separately because it's reused on every ECC call when the input
|
|
65
|
+
// is the same (constant golden / scan in a tight loop).
|
|
66
|
+
struct EccPreparedEntry {
|
|
67
|
+
cv::Mat prepared; // CV_32F, owned
|
|
68
|
+
bool ok; // matches PrepareAlignmentImage's return value
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// Feature-seed matrix: the entire ORB->BFMatcher->RANSAC pipeline output for
|
|
72
|
+
// a given (refFp, targetFp, motionFlag) combination. Caching this lets us
|
|
73
|
+
// skip the match + RANSAC stage when the input pair AND motion model haven't
|
|
74
|
+
// changed (the bench loop, and back-to-back calls in production with the
|
|
75
|
+
// same scan).
|
|
76
|
+
struct SeedMatrixEntry {
|
|
77
|
+
cv::Mat matrix; // either 2x3 (affine-family) or 3x3 (homography), CV_32F
|
|
78
|
+
bool ok; // false if RunFeatureSeed returned false
|
|
79
|
+
int inlierCount; // RANSAC inlier count, used by the smart-ECC-skip heuristic
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
template <typename T>
|
|
83
|
+
class FingerprintLRU {
|
|
84
|
+
public:
|
|
85
|
+
static FingerprintLRU& Get() {
|
|
86
|
+
static FingerprintLRU instance;
|
|
87
|
+
return instance;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
bool Lookup(uint64_t key, T& out) {
|
|
91
|
+
std::lock_guard<std::mutex> lg(mu_);
|
|
92
|
+
auto it = map_.find(key);
|
|
93
|
+
if (it == map_.end()) return false;
|
|
94
|
+
lru_.splice(lru_.begin(), lru_, it->second.lruIter);
|
|
95
|
+
out = it->second.entry;
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
void Insert(uint64_t key, T entry) {
|
|
100
|
+
std::lock_guard<std::mutex> lg(mu_);
|
|
101
|
+
auto it = map_.find(key);
|
|
102
|
+
if (it != map_.end()) {
|
|
103
|
+
it->second.entry = std::move(entry);
|
|
104
|
+
lru_.splice(lru_.begin(), lru_, it->second.lruIter);
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (map_.size() >= MAX_ENTRIES) {
|
|
108
|
+
uint64_t evict = lru_.back();
|
|
109
|
+
lru_.pop_back();
|
|
110
|
+
map_.erase(evict);
|
|
111
|
+
}
|
|
112
|
+
lru_.push_front(key);
|
|
113
|
+
MapValue v;
|
|
114
|
+
v.lruIter = lru_.begin();
|
|
115
|
+
v.entry = std::move(entry);
|
|
116
|
+
map_.emplace(key, std::move(v));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private:
|
|
120
|
+
static constexpr size_t MAX_ENTRIES = 16;
|
|
121
|
+
struct MapValue {
|
|
122
|
+
typename std::list<uint64_t>::iterator lruIter;
|
|
123
|
+
T entry;
|
|
124
|
+
};
|
|
125
|
+
std::mutex mu_;
|
|
126
|
+
std::list<uint64_t> lru_;
|
|
127
|
+
std::unordered_map<uint64_t, MapValue> map_;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// Small gray (downsampled grayscale) cache: keyed by the FULL-resolution input
|
|
131
|
+
// gray fingerprint, stores the resized small gray at the configured scale.
|
|
132
|
+
// Lets us skip cv::resize for repeated inputs (same golden across calls).
|
|
133
|
+
struct SmallGrayEntry {
|
|
134
|
+
cv::Mat smallGray;
|
|
135
|
+
int scaledWidth;
|
|
136
|
+
int scaledHeight;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
using OrbFeatureCache = FingerprintLRU<OrbCacheEntry>;
|
|
140
|
+
using EccPreparedCache = FingerprintLRU<EccPreparedEntry>;
|
|
141
|
+
using SeedMatrixCache = FingerprintLRU<SeedMatrixEntry>;
|
|
142
|
+
using SmallGrayCache = FingerprintLRU<SmallGrayEntry>;
|
|
143
|
+
|
|
144
|
+
} // namespace
|
|
145
|
+
|
|
146
|
+
// Map a config string to OpenCV's MOTION_* enum.
|
|
147
|
+
// Mirrors the small lookup helpers used elsewhere (e.g. color-convert.cpp).
|
|
148
|
+
static int ParseMotionModel(const std::string& name) {
|
|
149
|
+
if (name == "translation") return cv::MOTION_TRANSLATION;
|
|
150
|
+
if (name == "euclidean") return cv::MOTION_EUCLIDEAN;
|
|
151
|
+
if (name == "affine") return cv::MOTION_AFFINE;
|
|
152
|
+
if (name == "homography") return cv::MOTION_HOMOGRAPHY;
|
|
153
|
+
throw std::runtime_error("Unknown motionModel: " + name +
|
|
154
|
+
" (expected: translation, euclidean, affine, or homography)");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Pipeline modes for image-align:
|
|
158
|
+
// ECC - intensity-based ECC only, identity init (legacy default)
|
|
159
|
+
// FEATURES - ORB+RANSAC only, no ECC refinement
|
|
160
|
+
// FEATURES_ECC - ORB seed -> ECC refinement (best accuracy, recommended for new nodes)
|
|
161
|
+
enum class AlignPipeline { ECC, FEATURES, FEATURES_ECC };
|
|
162
|
+
|
|
163
|
+
static AlignPipeline ParsePipeline(const std::string& name) {
|
|
164
|
+
if (name == "ecc") return AlignPipeline::ECC;
|
|
165
|
+
if (name == "features") return AlignPipeline::FEATURES;
|
|
166
|
+
if (name == "features+ecc") return AlignPipeline::FEATURES_ECC;
|
|
167
|
+
throw std::runtime_error("Unknown pipeline: " + name +
|
|
168
|
+
" (expected: ecc, features, or features+ecc)");
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ECC refinement policy (only meaningful when pipeline == FEATURES_ECC):
|
|
172
|
+
// ALWAYS - run ECC refinement on every call (legacy default, preserves accuracy)
|
|
173
|
+
// AUTO - skip ECC when ORB+RANSAC inlier count >= threshold (much faster
|
|
174
|
+
// on clean feature-rich data; may sacrifice ~5-10% accuracy on
|
|
175
|
+
// edge cases). Threshold = 50 inliers.
|
|
176
|
+
// NEVER - never run ECC; equivalent to pipeline=features but keeps the
|
|
177
|
+
// features+ecc pipeline mode in the saved config.
|
|
178
|
+
enum class EccRefineMode { ALWAYS, AUTO, NEVER };
|
|
179
|
+
|
|
180
|
+
static EccRefineMode ParseEccRefine(const std::string& name) {
|
|
181
|
+
if (name == "always") return EccRefineMode::ALWAYS;
|
|
182
|
+
if (name == "auto") return EccRefineMode::AUTO;
|
|
183
|
+
if (name == "never") return EccRefineMode::NEVER;
|
|
184
|
+
throw std::runtime_error("Unknown eccRefine: " + name +
|
|
185
|
+
" (expected: always, auto, or never)");
|
|
186
|
+
}
|
|
187
|
+
|
|
15
188
|
class ImageAlignWorker : public Napi::AsyncWorker {
|
|
16
189
|
public:
|
|
17
190
|
ImageAlignWorker(Napi::Function& callback,
|
|
@@ -24,7 +197,10 @@ public:
|
|
|
24
197
|
int quality = 90,
|
|
25
198
|
bool pngOptimize = false,
|
|
26
199
|
bool returnMatrix = false,
|
|
27
|
-
const Napi::Value& polygonValue = Napi::Value()
|
|
200
|
+
const Napi::Value& polygonValue = Napi::Value(),
|
|
201
|
+
std::string motionModel = "translation",
|
|
202
|
+
std::string pipeline = "ecc",
|
|
203
|
+
std::string eccRefine = "always")
|
|
28
204
|
: Napi::AsyncWorker(callback),
|
|
29
205
|
scale(scale),
|
|
30
206
|
maxIterations(maxIterations),
|
|
@@ -33,13 +209,31 @@ public:
|
|
|
33
209
|
quality(quality),
|
|
34
210
|
pngOptimize(pngOptimize),
|
|
35
211
|
returnMatrix(returnMatrix),
|
|
212
|
+
motionModelName(std::move(motionModel)),
|
|
213
|
+
motionFlag(cv::MOTION_TRANSLATION),
|
|
214
|
+
useHomography(false),
|
|
215
|
+
pipelineName(std::move(pipeline)),
|
|
216
|
+
pipelineMode(AlignPipeline::ECC),
|
|
217
|
+
eccRefineName(std::move(eccRefine)),
|
|
218
|
+
eccRefineMode(EccRefineMode::ALWAYS),
|
|
36
219
|
alignmentSuccess(false),
|
|
37
220
|
hasPolygon(false),
|
|
38
221
|
isPolygonArray(false) {
|
|
39
222
|
|
|
40
223
|
try {
|
|
41
224
|
auto t0 = std::chrono::steady_clock::now();
|
|
42
|
-
|
|
225
|
+
|
|
226
|
+
// Resolve motion model string -> OpenCV enum once, up front, so any
|
|
227
|
+
// bad value fails synchronously instead of inside the worker thread.
|
|
228
|
+
motionFlag = ParseMotionModel(motionModelName);
|
|
229
|
+
useHomography = (motionFlag == cv::MOTION_HOMOGRAPHY);
|
|
230
|
+
|
|
231
|
+
// Same for pipeline mode (ecc / features / features+ecc).
|
|
232
|
+
pipelineMode = ParsePipeline(pipelineName);
|
|
233
|
+
|
|
234
|
+
// And the ECC refinement policy (always / auto / never).
|
|
235
|
+
eccRefineMode = ParseEccRefine(eccRefineName);
|
|
236
|
+
|
|
43
237
|
// Convert input images to OpenCV Mat
|
|
44
238
|
referenceMat = ConvertToMat(referenceImage);
|
|
45
239
|
targetMat = ConvertToMat(targetImage);
|
|
@@ -134,10 +328,27 @@ protected:
|
|
|
134
328
|
int refHeight = referenceMat.rows;
|
|
135
329
|
int refWidth = referenceMat.cols;
|
|
136
330
|
|
|
137
|
-
// Resize target image to match reference dimensions
|
|
331
|
+
// Resize target image to match reference dimensions, with caching.
|
|
332
|
+
// For the constant-golden / changing-scan production pattern, the
|
|
333
|
+
// golden's resize result is constant per call. Hash + cache it.
|
|
138
334
|
cv::Mat targetResized;
|
|
139
335
|
if (targetMat.size() != referenceMat.size()) {
|
|
140
|
-
|
|
336
|
+
const uint64_t key = FastImageFingerprint(targetMat)
|
|
337
|
+
^ (static_cast<uint64_t>(refWidth) << 16)
|
|
338
|
+
^ static_cast<uint64_t>(refHeight)
|
|
339
|
+
^ 0x7e57edcafef00dULL; // distinguish from other caches
|
|
340
|
+
SmallGrayEntry hit;
|
|
341
|
+
if (SmallGrayCache::Get().Lookup(key, hit) &&
|
|
342
|
+
hit.scaledWidth == refWidth && hit.scaledHeight == refHeight) {
|
|
343
|
+
targetResized = hit.smallGray;
|
|
344
|
+
} else {
|
|
345
|
+
cv::resize(targetMat, targetResized, cv::Size(refWidth, refHeight));
|
|
346
|
+
SmallGrayEntry e;
|
|
347
|
+
e.smallGray = targetResized.clone();
|
|
348
|
+
e.scaledWidth = refWidth;
|
|
349
|
+
e.scaledHeight = refHeight;
|
|
350
|
+
SmallGrayCache::Get().Insert(key, std::move(e));
|
|
351
|
+
}
|
|
141
352
|
} else {
|
|
142
353
|
targetResized = targetMat;
|
|
143
354
|
}
|
|
@@ -212,10 +423,16 @@ protected:
|
|
|
212
423
|
// Add transformation matrix if requested and alignment succeeded
|
|
213
424
|
if (returnMatrix && alignmentSuccess && !transformationMatrix.empty()) {
|
|
214
425
|
Napi::Object matrix = Napi::Object::New(env);
|
|
426
|
+
|
|
427
|
+
// dx/dy are the translation component in pixel space - meaningful
|
|
428
|
+
// for every motion model (the [0,2]/[1,2] elements of the matrix).
|
|
215
429
|
matrix.Set("dx", Napi::Number::New(env, transformationMatrix.at<float>(0, 2)));
|
|
216
430
|
matrix.Set("dy", Napi::Number::New(env, transformationMatrix.at<float>(1, 2)));
|
|
217
|
-
|
|
218
|
-
//
|
|
431
|
+
|
|
432
|
+
// matrix2x3: the upper 2 rows in OpenCV warp order [a,b,dx,c,d,dy].
|
|
433
|
+
// For affine-family this IS the warp; for homography it's the
|
|
434
|
+
// upper 2x3 block (still useful for callers that only care about
|
|
435
|
+
// the affine approximation).
|
|
219
436
|
Napi::Array matrix2x3 = Napi::Array::New(env, 6);
|
|
220
437
|
matrix2x3.Set(0u, Napi::Number::New(env, transformationMatrix.at<float>(0, 0)));
|
|
221
438
|
matrix2x3.Set(1u, Napi::Number::New(env, transformationMatrix.at<float>(0, 1)));
|
|
@@ -223,22 +440,39 @@ protected:
|
|
|
223
440
|
matrix2x3.Set(3u, Napi::Number::New(env, transformationMatrix.at<float>(1, 0)));
|
|
224
441
|
matrix2x3.Set(4u, Napi::Number::New(env, transformationMatrix.at<float>(1, 1)));
|
|
225
442
|
matrix2x3.Set(5u, Napi::Number::New(env, transformationMatrix.at<float>(1, 2)));
|
|
226
|
-
|
|
227
|
-
//
|
|
443
|
+
|
|
444
|
+
// matrix3x3: full homogeneous form. For affine-family the bottom
|
|
445
|
+
// row is the canonical [0,0,1]; for homography we read all 9
|
|
446
|
+
// elements straight out of the solved matrix.
|
|
228
447
|
Napi::Array matrix3x3 = Napi::Array::New(env, 9);
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
448
|
+
if (useHomography) {
|
|
449
|
+
matrix3x3.Set(0u, Napi::Number::New(env, transformationMatrix.at<float>(0, 0)));
|
|
450
|
+
matrix3x3.Set(1u, Napi::Number::New(env, transformationMatrix.at<float>(0, 1)));
|
|
451
|
+
matrix3x3.Set(2u, Napi::Number::New(env, transformationMatrix.at<float>(0, 2)));
|
|
452
|
+
matrix3x3.Set(3u, Napi::Number::New(env, transformationMatrix.at<float>(1, 0)));
|
|
453
|
+
matrix3x3.Set(4u, Napi::Number::New(env, transformationMatrix.at<float>(1, 1)));
|
|
454
|
+
matrix3x3.Set(5u, Napi::Number::New(env, transformationMatrix.at<float>(1, 2)));
|
|
455
|
+
matrix3x3.Set(6u, Napi::Number::New(env, transformationMatrix.at<float>(2, 0)));
|
|
456
|
+
matrix3x3.Set(7u, Napi::Number::New(env, transformationMatrix.at<float>(2, 1)));
|
|
457
|
+
matrix3x3.Set(8u, Napi::Number::New(env, transformationMatrix.at<float>(2, 2)));
|
|
458
|
+
} else {
|
|
459
|
+
matrix3x3.Set(0u, Napi::Number::New(env, transformationMatrix.at<float>(0, 0))); // m00
|
|
460
|
+
matrix3x3.Set(1u, Napi::Number::New(env, transformationMatrix.at<float>(0, 1))); // m01
|
|
461
|
+
matrix3x3.Set(2u, Napi::Number::New(env, transformationMatrix.at<float>(0, 2))); // m02 (dx)
|
|
462
|
+
matrix3x3.Set(3u, Napi::Number::New(env, transformationMatrix.at<float>(1, 0))); // m10
|
|
463
|
+
matrix3x3.Set(4u, Napi::Number::New(env, transformationMatrix.at<float>(1, 1))); // m11
|
|
464
|
+
matrix3x3.Set(5u, Napi::Number::New(env, transformationMatrix.at<float>(1, 2))); // m12 (dy)
|
|
465
|
+
matrix3x3.Set(6u, Napi::Number::New(env, 0.0)); // m20 (always 0)
|
|
466
|
+
matrix3x3.Set(7u, Napi::Number::New(env, 0.0)); // m21 (always 0)
|
|
467
|
+
matrix3x3.Set(8u, Napi::Number::New(env, 1.0)); // m22 (always 1)
|
|
468
|
+
}
|
|
469
|
+
|
|
239
470
|
matrix.Set("matrix2x3", matrix2x3); // OpenCV format [a,b,dx,c,d,dy]
|
|
240
471
|
matrix.Set("matrix3x3", matrix3x3); // Standard homogeneous format
|
|
241
472
|
matrix.Set("transform", matrix3x3); // Alias for backward compatibility
|
|
473
|
+
matrix.Set("motionModel", Napi::String::New(env, motionModelName));
|
|
474
|
+
matrix.Set("pipeline", Napi::String::New(env, pipelineName));
|
|
475
|
+
matrix.Set("eccRefine", Napi::String::New(env, eccRefineName));
|
|
242
476
|
response.Set("transformMatrix", matrix);
|
|
243
477
|
}
|
|
244
478
|
|
|
@@ -297,6 +531,20 @@ private:
|
|
|
297
531
|
cv::Mat referenceMat, targetMat, alignedImage;
|
|
298
532
|
cv::Mat transformationMatrix;
|
|
299
533
|
std::string referenceChannelOrder, targetChannelOrder, outputChannelOrder;
|
|
534
|
+
|
|
535
|
+
// Motion model selection
|
|
536
|
+
std::string motionModelName; // raw string from JS ('translation' | 'euclidean' | 'affine' | 'homography')
|
|
537
|
+
int motionFlag; // resolved cv::MOTION_* enum
|
|
538
|
+
bool useHomography; // true iff motionFlag == MOTION_HOMOGRAPHY (3x3 matrix)
|
|
539
|
+
|
|
540
|
+
// Pipeline selection (which alignment algorithm(s) to run)
|
|
541
|
+
std::string pipelineName; // raw string from JS ('ecc' | 'features' | 'features+ecc')
|
|
542
|
+
AlignPipeline pipelineMode; // resolved enum
|
|
543
|
+
|
|
544
|
+
// ECC refinement policy (only meaningful when pipelineMode == FEATURES_ECC)
|
|
545
|
+
std::string eccRefineName; // raw string from JS ('always' | 'auto' | 'never')
|
|
546
|
+
EccRefineMode eccRefineMode; // resolved enum
|
|
547
|
+
|
|
300
548
|
bool alignmentSuccess;
|
|
301
549
|
|
|
302
550
|
// Polygon data
|
|
@@ -358,124 +606,460 @@ private:
|
|
|
358
606
|
return true;
|
|
359
607
|
}
|
|
360
608
|
|
|
361
|
-
//
|
|
609
|
+
// Run an ORB feature-matching pre-alignment between two grayscale images.
|
|
610
|
+
// Returns true on success and writes the transform matrix into `outMatrix`,
|
|
611
|
+
// shaped to match the requested motion model:
|
|
612
|
+
// - MOTION_HOMOGRAPHY -> 3x3 (cv::findHomography)
|
|
613
|
+
// - MOTION_AFFINE -> 2x3 (cv::estimateAffine2D, full 6-DoF)
|
|
614
|
+
// - MOTION_EUCLIDEAN -> 2x3 (estimateAffinePartial2D, scale normalized to 1)
|
|
615
|
+
// - MOTION_TRANSLATION -> 2x3 (estimateAffinePartial2D, linear part = identity)
|
|
616
|
+
//
|
|
617
|
+
// The output coordinate space is the same as the input grayscale Mats:
|
|
618
|
+
// callers are responsible for any further rescaling (e.g. to full resolution).
|
|
619
|
+
bool RunFeatureSeed(const cv::Mat& refGray, const cv::Mat& targetGray,
|
|
620
|
+
int motionFlagLocal, cv::Mat& outMatrix,
|
|
621
|
+
int* outInlierCount = nullptr) const {
|
|
622
|
+
try {
|
|
623
|
+
// First check the seed-matrix cache: if we've already solved this
|
|
624
|
+
// 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);
|
|
628
|
+
// Composite key: mix the two fingerprints with the motion flag.
|
|
629
|
+
uint64_t seedKey = refFp;
|
|
630
|
+
seedKey ^= targetFp + 0x9e3779b97f4a7c15ULL + (seedKey << 6) + (seedKey >> 2);
|
|
631
|
+
seedKey ^= static_cast<uint64_t>(motionFlagLocal) * 0x9e3779b97f4a7c15ULL;
|
|
632
|
+
{
|
|
633
|
+
SeedMatrixEntry hit;
|
|
634
|
+
if (SeedMatrixCache::Get().Lookup(seedKey, hit)) {
|
|
635
|
+
if (!hit.ok) return false;
|
|
636
|
+
// The caller (FindTransformation -> RescaleSmallToFull) MUTATES
|
|
637
|
+
// the returned matrix in-place to rescale it to full resolution.
|
|
638
|
+
// We must clone here so we don't corrupt the cached entry across
|
|
639
|
+
// successive calls.
|
|
640
|
+
outMatrix = hit.matrix.clone();
|
|
641
|
+
if (outInlierCount) *outInlierCount = hit.inlierCount;
|
|
642
|
+
return true;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
cv::Ptr<cv::ORB> orb = cv::ORB::create(
|
|
647
|
+
/*nfeatures*/ 800,
|
|
648
|
+
/*scaleFactor*/ 1.2f,
|
|
649
|
+
/*nlevels*/ 5);
|
|
650
|
+
|
|
651
|
+
// Detect-or-cache helper. Looks up by FastImageFingerprint and skips
|
|
652
|
+
// ORB entirely on cache hit. The big win is the "constant golden,
|
|
653
|
+
// changing scan" pattern: golden hits the cache from call #2 onward.
|
|
654
|
+
auto detectOrCached = [&orb](const cv::Mat& img, uint64_t fp,
|
|
655
|
+
std::vector<cv::KeyPoint>& kp,
|
|
656
|
+
cv::Mat& des) {
|
|
657
|
+
OrbCacheEntry hit;
|
|
658
|
+
if (OrbFeatureCache::Get().Lookup(fp, hit)) {
|
|
659
|
+
kp = hit.kp;
|
|
660
|
+
des = hit.des;
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
orb->detectAndCompute(img, cv::noArray(), kp, des);
|
|
664
|
+
OrbCacheEntry e;
|
|
665
|
+
e.kp = kp;
|
|
666
|
+
e.des = des.clone(); // detach storage
|
|
667
|
+
OrbFeatureCache::Get().Insert(fp, std::move(e));
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
// Inner solve - returns true and writes outMatrix on success.
|
|
671
|
+
// Wrapped so we can record the (success, matrix) pair into the
|
|
672
|
+
// seed-matrix cache once at the end without repeating inserts.
|
|
673
|
+
auto solve = [&]() -> bool {
|
|
674
|
+
// Parallel ORB extraction: scan and golden run on separate
|
|
675
|
+
// threads. The golden side is usually a cache hit so it's near
|
|
676
|
+
// free, but the threading overhead is small enough that it's
|
|
677
|
+
// still a net win when both sides do real work (cold start).
|
|
678
|
+
std::vector<cv::KeyPoint> kp1, kp2;
|
|
679
|
+
cv::Mat des1, des2;
|
|
680
|
+
auto fut2 = std::async(std::launch::async, [&]() {
|
|
681
|
+
detectOrCached(targetGray, targetFp, kp2, des2);
|
|
682
|
+
});
|
|
683
|
+
detectOrCached(refGray, refFp, kp1, des1);
|
|
684
|
+
fut2.get();
|
|
685
|
+
|
|
686
|
+
if (des1.empty() || des2.empty() || kp1.size() < 10 || kp2.size() < 10) {
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// Brute-force Hamming + Lowe's ratio test (0.75) for robust matching.
|
|
691
|
+
cv::BFMatcher matcher(cv::NORM_HAMMING, /*crossCheck=*/false);
|
|
692
|
+
std::vector<std::vector<cv::DMatch>> knn;
|
|
693
|
+
matcher.knnMatch(des1, des2, knn, 2);
|
|
694
|
+
|
|
695
|
+
std::vector<cv::Point2f> srcPts, dstPts;
|
|
696
|
+
srcPts.reserve(knn.size());
|
|
697
|
+
dstPts.reserve(knn.size());
|
|
698
|
+
for (const auto& pair : knn) {
|
|
699
|
+
if (pair.size() < 2) continue;
|
|
700
|
+
if (pair[0].distance < 0.75f * pair[1].distance) {
|
|
701
|
+
srcPts.push_back(kp1[pair[0].queryIdx].pt);
|
|
702
|
+
dstPts.push_back(kp2[pair[0].trainIdx].pt);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// Need a minimum number of correspondences for any robust estimator.
|
|
707
|
+
if (srcPts.size() < 12) {
|
|
708
|
+
return false;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
cv::Mat inlierMask;
|
|
712
|
+
if (motionFlagLocal == cv::MOTION_HOMOGRAPHY) {
|
|
713
|
+
cv::Mat H = cv::findHomography(srcPts, dstPts, cv::USAC_MAGSAC, 5.0, inlierMask);
|
|
714
|
+
if (H.empty()) return false;
|
|
715
|
+
H.convertTo(outMatrix, CV_32F);
|
|
716
|
+
if (outInlierCount) *outInlierCount = cv::countNonZero(inlierMask);
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (motionFlagLocal == cv::MOTION_AFFINE) {
|
|
721
|
+
cv::Mat A = cv::estimateAffine2D(srcPts, dstPts, inlierMask,
|
|
722
|
+
cv::USAC_MAGSAC, 5.0);
|
|
723
|
+
if (A.empty()) return false;
|
|
724
|
+
A.convertTo(outMatrix, CV_32F);
|
|
725
|
+
if (outInlierCount) *outInlierCount = cv::countNonZero(inlierMask);
|
|
726
|
+
return true;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Translation and Euclidean both start from a partial-affine estimate
|
|
730
|
+
// (translation + rotation + uniform scale = 4 DoF), then post-process
|
|
731
|
+
// it to drop the unwanted DoFs.
|
|
732
|
+
cv::Mat P = cv::estimateAffinePartial2D(srcPts, dstPts, inlierMask,
|
|
733
|
+
cv::USAC_MAGSAC, 5.0);
|
|
734
|
+
if (P.empty()) return false;
|
|
735
|
+
P.convertTo(P, CV_32F);
|
|
736
|
+
|
|
737
|
+
if (outInlierCount) *outInlierCount = cv::countNonZero(inlierMask);
|
|
738
|
+
|
|
739
|
+
if (motionFlagLocal == cv::MOTION_EUCLIDEAN) {
|
|
740
|
+
float a = P.at<float>(0, 0);
|
|
741
|
+
float c = P.at<float>(1, 0);
|
|
742
|
+
float s = std::sqrt(a * a + c * c);
|
|
743
|
+
if (s > 1e-6f) {
|
|
744
|
+
P.at<float>(0, 0) /= s;
|
|
745
|
+
P.at<float>(0, 1) /= s;
|
|
746
|
+
P.at<float>(1, 0) /= s;
|
|
747
|
+
P.at<float>(1, 1) /= s;
|
|
748
|
+
}
|
|
749
|
+
outMatrix = P;
|
|
750
|
+
return true;
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
// MOTION_TRANSLATION (or any unknown 2x3 case): keep only tx/ty.
|
|
754
|
+
outMatrix = (cv::Mat_<float>(2, 3) <<
|
|
755
|
+
1.0f, 0.0f, P.at<float>(0, 2),
|
|
756
|
+
0.0f, 1.0f, P.at<float>(1, 2));
|
|
757
|
+
return true;
|
|
758
|
+
};
|
|
759
|
+
|
|
760
|
+
const bool ok = solve();
|
|
761
|
+
|
|
762
|
+
// Record into the seed-matrix cache so future calls with the same
|
|
763
|
+
// (ref, target, motion) skip everything above. Inlier count is
|
|
764
|
+
// saved so cache hits can also feed the smart-ECC-skip heuristic.
|
|
765
|
+
SeedMatrixEntry entry;
|
|
766
|
+
entry.ok = ok;
|
|
767
|
+
entry.inlierCount = outInlierCount ? *outInlierCount : 0;
|
|
768
|
+
if (ok) entry.matrix = outMatrix.clone();
|
|
769
|
+
SeedMatrixCache::Get().Insert(seedKey, std::move(entry));
|
|
770
|
+
|
|
771
|
+
return ok;
|
|
772
|
+
|
|
773
|
+
} catch (const cv::Exception&) {
|
|
774
|
+
return false;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// Rescale a small-frame transform matrix back to full-resolution coordinates.
|
|
779
|
+
// The math depends on matrix shape: see the homography derivation note inline.
|
|
780
|
+
void RescaleSmallToFull(cv::Mat& m) const {
|
|
781
|
+
const float s = static_cast<float>(scale);
|
|
782
|
+
if (useHomography) {
|
|
783
|
+
// H_full = diag(1/s, 1/s, 1) * H_small * diag(s, s, 1)
|
|
784
|
+
// - rotation/scale block (rows 0-1, cols 0-1) is unchanged
|
|
785
|
+
// - translation column (rows 0-1, col 2) is divided by s
|
|
786
|
+
// - perspective row (row 2, cols 0-1) is multiplied by s
|
|
787
|
+
// - bottom-right (row 2, col 2) is unchanged
|
|
788
|
+
m.at<float>(0, 2) /= s;
|
|
789
|
+
m.at<float>(1, 2) /= s;
|
|
790
|
+
m.at<float>(2, 0) *= s;
|
|
791
|
+
m.at<float>(2, 1) *= s;
|
|
792
|
+
} else {
|
|
793
|
+
// 2x3 affine-family: only the translation column needs rescaling.
|
|
794
|
+
m.at<float>(0, 2) /= s;
|
|
795
|
+
m.at<float>(1, 2) /= s;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// Find transformation matrix - dispatches on the configured pipeline:
|
|
800
|
+
// ECC -> identity init -> findTransformECC (legacy path)
|
|
801
|
+
// FEATURES -> ORB+RANSAC seed only, no ECC
|
|
802
|
+
// FEATURES_ECC -> ORB seed -> findTransformECC refinement.
|
|
803
|
+
// If ECC diverges, fall back to the seed (still useful)
|
|
804
|
+
// instead of returning a wildly wrong identity warp.
|
|
362
805
|
bool FindTransformation(const cv::Mat& refGray, const cv::Mat& targetGray, cv::Mat& transformMatrix) {
|
|
363
806
|
try {
|
|
364
807
|
int height = refGray.rows;
|
|
365
808
|
int width = refGray.cols;
|
|
366
|
-
|
|
367
|
-
// Downsample images for faster alignment
|
|
809
|
+
|
|
810
|
+
// 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().
|
|
368
814
|
int scaledWidth = std::max(1, static_cast<int>(std::round(width * scale)));
|
|
369
815
|
int scaledHeight = std::max(1, static_cast<int>(std::round(height * scale)));
|
|
370
|
-
|
|
816
|
+
|
|
817
|
+
// Cached resize: skips cv::resize when the input gray hasn't changed
|
|
818
|
+
// (constant-golden, repeated-call pattern). Lookup is keyed by the
|
|
819
|
+
// FULL-resolution input fingerprint AND the requested small dims.
|
|
820
|
+
auto resizeOrCached = [scaledWidth, scaledHeight](const cv::Mat& fullGray,
|
|
821
|
+
cv::Mat& smallOut) {
|
|
822
|
+
const uint64_t key = FastImageFingerprint(fullGray)
|
|
823
|
+
^ (static_cast<uint64_t>(scaledWidth) << 16)
|
|
824
|
+
^ static_cast<uint64_t>(scaledHeight);
|
|
825
|
+
SmallGrayEntry hit;
|
|
826
|
+
if (SmallGrayCache::Get().Lookup(key, hit) &&
|
|
827
|
+
hit.scaledWidth == scaledWidth && hit.scaledHeight == scaledHeight) {
|
|
828
|
+
smallOut = hit.smallGray; // share data; downstream readers don't mutate
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
cv::resize(fullGray, smallOut, cv::Size(scaledWidth, scaledHeight));
|
|
832
|
+
SmallGrayEntry e;
|
|
833
|
+
e.smallGray = smallOut.clone();
|
|
834
|
+
e.scaledWidth = scaledWidth;
|
|
835
|
+
e.scaledHeight = scaledHeight;
|
|
836
|
+
SmallGrayCache::Get().Insert(key, std::move(e));
|
|
837
|
+
};
|
|
838
|
+
|
|
371
839
|
cv::Mat refSmall, targetSmall;
|
|
372
|
-
|
|
373
|
-
|
|
840
|
+
resizeOrCached(refGray, refSmall);
|
|
841
|
+
resizeOrCached(targetGray, targetSmall);
|
|
842
|
+
|
|
843
|
+
// -------- Stage 1: optional ORB feature seed -----------------
|
|
844
|
+
cv::Mat seedMatrix; // small-frame coords
|
|
845
|
+
int seedInliers = 0;
|
|
846
|
+
bool haveSeed = false;
|
|
847
|
+
if (pipelineMode == AlignPipeline::FEATURES ||
|
|
848
|
+
pipelineMode == AlignPipeline::FEATURES_ECC) {
|
|
849
|
+
// Only ask RANSAC for the inlier count when the smart-skip
|
|
850
|
+
// policy actually needs it (saves a tiny cv::countNonZero call).
|
|
851
|
+
int* inlierOut = (eccRefineMode == EccRefineMode::AUTO) ? &seedInliers : nullptr;
|
|
852
|
+
haveSeed = RunFeatureSeed(refSmall, targetSmall, motionFlag, seedMatrix, inlierOut);
|
|
853
|
+
if (!haveSeed && pipelineMode == AlignPipeline::FEATURES) {
|
|
854
|
+
// Features-only and we couldn't find a seed -> can't recover.
|
|
855
|
+
return false;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// -------- Features-only path: skip ECC entirely --------------
|
|
860
|
+
if (pipelineMode == AlignPipeline::FEATURES) {
|
|
861
|
+
transformMatrix = seedMatrix; // already in small-frame coords
|
|
862
|
+
RescaleSmallToFull(transformMatrix);
|
|
863
|
+
return true;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// -------- Smart ECC skip (opt-in via eccRefine config) --------
|
|
867
|
+
// FEATURES_ECC + eccRefine='never': always skip ECC after a good seed.
|
|
868
|
+
// FEATURES_ECC + eccRefine='auto': skip ECC when the seed is high-
|
|
869
|
+
// confidence (>=50 inliers from RANSAC),
|
|
870
|
+
// keeping ECC's accuracy benefit only
|
|
871
|
+
// on edge cases where features are weak.
|
|
872
|
+
if (pipelineMode == AlignPipeline::FEATURES_ECC && haveSeed) {
|
|
873
|
+
const bool skipForNever = (eccRefineMode == EccRefineMode::NEVER);
|
|
874
|
+
const bool skipForAuto = (eccRefineMode == EccRefineMode::AUTO &&
|
|
875
|
+
seedInliers >= 50);
|
|
876
|
+
if (skipForNever || skipForAuto) {
|
|
877
|
+
transformMatrix = seedMatrix;
|
|
878
|
+
RescaleSmallToFull(transformMatrix);
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// -------- ECC path (with or without feature seed) ------------
|
|
884
|
+
// Normalize exposure/contrast so ECC is less sensitive to lighting changes.
|
|
885
|
+
// The float32 prepared images are cached the same way as ORB features
|
|
886
|
+
// so repeated calls on the same input pair skip this work.
|
|
887
|
+
auto prepareOrCached = [this](const cv::Mat& src,
|
|
888
|
+
cv::Mat& outPrepared,
|
|
889
|
+
bool& outOk) {
|
|
890
|
+
const uint64_t key = FastImageFingerprint(src);
|
|
891
|
+
EccPreparedEntry hit;
|
|
892
|
+
if (EccPreparedCache::Get().Lookup(key, hit)) {
|
|
893
|
+
outPrepared = hit.prepared; // share data; ECC reads, doesn't write
|
|
894
|
+
outOk = hit.ok;
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
outOk = const_cast<ImageAlignWorker*>(this)->PrepareAlignmentImage(src, outPrepared);
|
|
898
|
+
EccPreparedEntry e;
|
|
899
|
+
e.prepared = outPrepared.clone();
|
|
900
|
+
e.ok = outOk;
|
|
901
|
+
EccPreparedCache::Get().Insert(key, std::move(e));
|
|
902
|
+
};
|
|
374
903
|
|
|
375
|
-
// Normalize exposure/contrast differences so ECC is less sensitive to lighting changes
|
|
376
904
|
cv::Mat refPrepared, targetPrepared;
|
|
377
|
-
bool refPreparedOk =
|
|
378
|
-
|
|
905
|
+
bool refPreparedOk = false, targetPreparedOk = false;
|
|
906
|
+
prepareOrCached(refSmall, refPrepared, refPreparedOk);
|
|
907
|
+
prepareOrCached(targetSmall, targetPrepared, targetPreparedOk);
|
|
379
908
|
|
|
380
909
|
if (!refPreparedOk || !targetPreparedOk) {
|
|
381
|
-
// Fallback to min-max normalization when variance is extremely low
|
|
910
|
+
// Fallback to min-max normalization when variance is extremely low.
|
|
911
|
+
// Note: we may have just shared cache data here. Clone first so we
|
|
912
|
+
// don't mutate the cached entry.
|
|
913
|
+
cv::Mat refClone, tgtClone;
|
|
914
|
+
refPrepared.copyTo(refClone);
|
|
915
|
+
targetPrepared.copyTo(tgtClone);
|
|
916
|
+
refPrepared = refClone;
|
|
917
|
+
targetPrepared = tgtClone;
|
|
382
918
|
cv::normalize(refPrepared, refPrepared, 0.0f, 1.0f, cv::NORM_MINMAX);
|
|
383
919
|
cv::normalize(targetPrepared, targetPrepared, 0.0f, 1.0f, cv::NORM_MINMAX);
|
|
384
920
|
}
|
|
385
|
-
|
|
386
|
-
// Initialize
|
|
387
|
-
|
|
388
|
-
|
|
921
|
+
|
|
922
|
+
// Initialize ECC's matrix. If we have a feature seed, use it as the
|
|
923
|
+
// starting guess; otherwise start from identity (legacy behavior).
|
|
924
|
+
if (haveSeed) {
|
|
925
|
+
transformMatrix = seedMatrix.clone();
|
|
926
|
+
} else if (useHomography) {
|
|
927
|
+
transformMatrix = cv::Mat::eye(3, 3, CV_32F);
|
|
928
|
+
} else {
|
|
929
|
+
transformMatrix = cv::Mat::eye(2, 3, CV_32F);
|
|
930
|
+
}
|
|
931
|
+
|
|
389
932
|
// Set up termination criteria
|
|
390
|
-
cv::TermCriteria criteria(cv::TermCriteria::COUNT | cv::TermCriteria::EPS,
|
|
933
|
+
cv::TermCriteria criteria(cv::TermCriteria::COUNT | cv::TermCriteria::EPS,
|
|
391
934
|
maxIterations, terminationEps);
|
|
392
|
-
|
|
393
|
-
//
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
935
|
+
|
|
936
|
+
// Run ECC. It may throw "iterations do not converge" - that's not
|
|
937
|
+
// necessarily fatal when we have a seed to fall back to.
|
|
938
|
+
double correlation = -1.0;
|
|
939
|
+
bool eccOk = false;
|
|
940
|
+
try {
|
|
941
|
+
correlation = cv::findTransformECC(refPrepared, targetPrepared, transformMatrix,
|
|
942
|
+
motionFlag, criteria);
|
|
943
|
+
eccOk = (correlation > 0.1);
|
|
944
|
+
} catch (const cv::Exception&) {
|
|
945
|
+
eccOk = false;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
if (!eccOk && haveSeed) {
|
|
949
|
+
// ECC diverged but we still have a usable feature seed -
|
|
950
|
+
// return it instead of failing the whole alignment.
|
|
951
|
+
transformMatrix = seedMatrix;
|
|
952
|
+
RescaleSmallToFull(transformMatrix);
|
|
953
|
+
return true;
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
if (!eccOk) {
|
|
957
|
+
// ECC-only pipeline and no convergence -> alignment failed.
|
|
958
|
+
return false;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
// ECC succeeded: rescale its small-frame result to full resolution.
|
|
962
|
+
RescaleSmallToFull(transformMatrix);
|
|
963
|
+
return true;
|
|
964
|
+
|
|
403
965
|
} catch (const cv::Exception& e) {
|
|
404
966
|
return false;
|
|
405
967
|
}
|
|
406
968
|
}
|
|
407
969
|
|
|
408
|
-
// Apply transformation to image
|
|
970
|
+
// Apply transformation to image - branches on motion model shape
|
|
409
971
|
void ApplyTransformation(const cv::Mat& target, const cv::Mat& transformMatrix, const cv::Size& size) {
|
|
410
972
|
try {
|
|
411
|
-
|
|
412
|
-
|
|
973
|
+
if (useHomography) {
|
|
974
|
+
cv::warpPerspective(target, alignedImage, transformMatrix, size,
|
|
975
|
+
cv::INTER_NEAREST | cv::WARP_INVERSE_MAP);
|
|
976
|
+
} else {
|
|
977
|
+
cv::warpAffine(target, alignedImage, transformMatrix, size,
|
|
978
|
+
cv::INTER_NEAREST | cv::WARP_INVERSE_MAP);
|
|
979
|
+
}
|
|
413
980
|
} catch (const cv::Exception& e) {
|
|
414
981
|
// If transformation fails, use original
|
|
415
982
|
alignedImage = target;
|
|
416
983
|
}
|
|
417
984
|
}
|
|
418
985
|
|
|
986
|
+
// Compute the inverse of the ECC matrix in the shape required by the
|
|
987
|
+
// chosen motion model. ApplyTransformation uses WARP_INVERSE_MAP, so the
|
|
988
|
+
// forward "image-space warp" is the inverse of `transformMatrix`; that's
|
|
989
|
+
// also the matrix we need to remap polygon points along with the image.
|
|
990
|
+
cv::Mat ComputeInverseMatrix(const cv::Mat& transformMatrix) const {
|
|
991
|
+
cv::Mat inv;
|
|
992
|
+
if (useHomography) {
|
|
993
|
+
// 3x3 homography: full inverse via LU.
|
|
994
|
+
cv::invert(transformMatrix, inv, cv::DECOMP_LU);
|
|
995
|
+
} else {
|
|
996
|
+
// 2x3 affine-family: OpenCV has a dedicated, faster inverter.
|
|
997
|
+
cv::invertAffineTransform(transformMatrix, inv);
|
|
998
|
+
}
|
|
999
|
+
return inv;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// Apply the (already-inverted) ECC matrix to a single polygon's points.
|
|
1003
|
+
// Input/output points are in normalized [0,1] coordinates relative to the
|
|
1004
|
+
// reference image dimensions (width x height).
|
|
1005
|
+
//
|
|
1006
|
+
// For MOTION_TRANSLATION the 2x3 inverse is [[1,0,-dx],[0,1,-dy]] and
|
|
1007
|
+
// cv::transform reduces to (x-dx, y-dy) -- bit-identical to the previous
|
|
1008
|
+
// hand-rolled implementation.
|
|
1009
|
+
void TransformPolygonPoints(const std::vector<cv::Point2f>& polygon,
|
|
1010
|
+
const cv::Mat& invMatrix,
|
|
1011
|
+
int width, int height,
|
|
1012
|
+
std::vector<cv::Point2f>& out) const {
|
|
1013
|
+
out.clear();
|
|
1014
|
+
if (polygon.empty()) {
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// Convert normalized -> pixel coordinates in reference space.
|
|
1019
|
+
std::vector<cv::Point2f> pxPts;
|
|
1020
|
+
pxPts.reserve(polygon.size());
|
|
1021
|
+
for (const auto& p : polygon) {
|
|
1022
|
+
pxPts.emplace_back(p.x * static_cast<float>(width),
|
|
1023
|
+
p.y * static_cast<float>(height));
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
// Apply the inverse warp using the appropriate OpenCV primitive.
|
|
1027
|
+
std::vector<cv::Point2f> outPts;
|
|
1028
|
+
if (useHomography) {
|
|
1029
|
+
cv::perspectiveTransform(pxPts, outPts, invMatrix);
|
|
1030
|
+
} else {
|
|
1031
|
+
cv::transform(pxPts, outPts, invMatrix);
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// Back to normalized [0,1], clamped to the valid range.
|
|
1035
|
+
out.reserve(outPts.size());
|
|
1036
|
+
const float invW = 1.0f / static_cast<float>(width);
|
|
1037
|
+
const float invH = 1.0f / static_cast<float>(height);
|
|
1038
|
+
for (const auto& q : outPts) {
|
|
1039
|
+
float nx = std::max(0.0f, std::min(1.0f, q.x * invW));
|
|
1040
|
+
float ny = std::max(0.0f, std::min(1.0f, q.y * invH));
|
|
1041
|
+
out.emplace_back(nx, ny);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
419
1045
|
// Transform single polygon coordinates
|
|
420
1046
|
void TransformPolygon(const std::vector<cv::Point2f>& polygon, const cv::Mat& transformMatrix, int width, int height) {
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
for (const auto& point : polygon) {
|
|
425
|
-
// Convert from normalized (0-1) to pixel coordinates
|
|
426
|
-
float px = point.x * width;
|
|
427
|
-
float py = point.y * height;
|
|
428
|
-
|
|
429
|
-
// Apply the transformation matrix
|
|
430
|
-
// Since we're using WARP_INVERSE_MAP, we need to apply the inverse transform
|
|
431
|
-
// For translation-only (2x3 matrix with identity rotation), the inverse is just negating the translation
|
|
432
|
-
float transformedX = px - transformMatrix.at<float>(0, 2);
|
|
433
|
-
float transformedY = py - transformMatrix.at<float>(1, 2);
|
|
434
|
-
|
|
435
|
-
// Convert back to normalized coordinates
|
|
436
|
-
float normalizedX = transformedX / width;
|
|
437
|
-
float normalizedY = transformedY / height;
|
|
438
|
-
|
|
439
|
-
// Clamp to valid range [0, 1]
|
|
440
|
-
normalizedX = std::max(0.0f, std::min(1.0f, normalizedX));
|
|
441
|
-
normalizedY = std::max(0.0f, std::min(1.0f, normalizedY));
|
|
442
|
-
|
|
443
|
-
transformedPolygon.push_back(cv::Point2f(normalizedX, normalizedY));
|
|
444
|
-
}
|
|
1047
|
+
const cv::Mat invMatrix = ComputeInverseMatrix(transformMatrix);
|
|
1048
|
+
TransformPolygonPoints(polygon, invMatrix, width, height, transformedPolygon);
|
|
445
1049
|
}
|
|
446
|
-
|
|
1050
|
+
|
|
447
1051
|
// Transform multiple polygons coordinates
|
|
448
1052
|
void TransformPolygons(const std::vector<std::vector<cv::Point2f>>& polygons, const cv::Mat& transformMatrix, int width, int height) {
|
|
449
1053
|
transformedPolygons.clear();
|
|
450
1054
|
transformedPolygons.reserve(polygons.size());
|
|
451
|
-
|
|
1055
|
+
|
|
1056
|
+
// Invert once, reuse across every polygon in the batch.
|
|
1057
|
+
const cv::Mat invMatrix = ComputeInverseMatrix(transformMatrix);
|
|
1058
|
+
|
|
452
1059
|
for (const auto& polygon : polygons) {
|
|
453
1060
|
std::vector<cv::Point2f> transformedPoly;
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
for (const auto& point : polygon) {
|
|
457
|
-
// Convert from normalized (0-1) to pixel coordinates
|
|
458
|
-
float px = point.x * width;
|
|
459
|
-
float py = point.y * height;
|
|
460
|
-
|
|
461
|
-
// Apply the transformation matrix
|
|
462
|
-
// Since we're using WARP_INVERSE_MAP, we need to apply the inverse transform
|
|
463
|
-
// For translation-only (2x3 matrix with identity rotation), the inverse is just negating the translation
|
|
464
|
-
float transformedX = px - transformMatrix.at<float>(0, 2);
|
|
465
|
-
float transformedY = py - transformMatrix.at<float>(1, 2);
|
|
466
|
-
|
|
467
|
-
// Convert back to normalized coordinates
|
|
468
|
-
float normalizedX = transformedX / width;
|
|
469
|
-
float normalizedY = transformedY / height;
|
|
470
|
-
|
|
471
|
-
// Clamp to valid range [0, 1]
|
|
472
|
-
normalizedX = std::max(0.0f, std::min(1.0f, normalizedX));
|
|
473
|
-
normalizedY = std::max(0.0f, std::min(1.0f, normalizedY));
|
|
474
|
-
|
|
475
|
-
transformedPoly.push_back(cv::Point2f(normalizedX, normalizedY));
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
transformedPolygons.push_back(transformedPoly);
|
|
1061
|
+
TransformPolygonPoints(polygon, invMatrix, width, height, transformedPoly);
|
|
1062
|
+
transformedPolygons.push_back(std::move(transformedPoly));
|
|
479
1063
|
}
|
|
480
1064
|
}
|
|
481
1065
|
};
|
|
@@ -483,19 +1067,19 @@ private:
|
|
|
483
1067
|
// Main function exported to Node.js
|
|
484
1068
|
Napi::Value ImageAlign(const Napi::CallbackInfo& info) {
|
|
485
1069
|
Napi::Env env = info.Env();
|
|
486
|
-
|
|
1070
|
+
|
|
487
1071
|
// Validate arguments - expect callback as last argument
|
|
488
|
-
if (info.Length() < 3 || info.Length() >
|
|
489
|
-
Napi::TypeError::New(env, "imageAlign(referenceImage, targetImage, [scale], [maxIterations], [terminationEps], [outputFormat], [quality], [pngOptimize], [returnMatrix], [polygon], callback)")
|
|
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)")
|
|
490
1074
|
.ThrowAsJavaScriptException();
|
|
491
1075
|
return env.Null();
|
|
492
1076
|
}
|
|
493
|
-
|
|
1077
|
+
|
|
494
1078
|
// Extract required arguments
|
|
495
1079
|
Napi::Value referenceImage = info[0];
|
|
496
1080
|
Napi::Value targetImage = info[1];
|
|
497
1081
|
Napi::Function callback = info[info.Length() - 1].As<Napi::Function>();
|
|
498
|
-
|
|
1082
|
+
|
|
499
1083
|
// Handle optional parameters with defaults
|
|
500
1084
|
double scale = 0.2; // Ultra-fast preset default
|
|
501
1085
|
int maxIterations = 10;
|
|
@@ -505,47 +1089,55 @@ Napi::Value ImageAlign(const Napi::CallbackInfo& info) {
|
|
|
505
1089
|
bool pngOptimize = false;
|
|
506
1090
|
bool returnMatrix = false;
|
|
507
1091
|
Napi::Value polygon = env.Null();
|
|
508
|
-
|
|
509
|
-
|
|
1092
|
+
// Default to translation so any caller that forgets to pass motionModel
|
|
1093
|
+
// continues to behave exactly like the pre-extension node.
|
|
1094
|
+
std::string motionModel = "translation";
|
|
1095
|
+
// Default pipeline is ECC-only for the same back-compat reason.
|
|
1096
|
+
std::string pipeline = "ecc";
|
|
1097
|
+
// Default eccRefine is "always" - never silently skips ECC.
|
|
1098
|
+
std::string eccRefine = "always";
|
|
1099
|
+
|
|
510
1100
|
// Parse optional parameters (before callback)
|
|
511
1101
|
if (info.Length() >= 4) {
|
|
512
1102
|
scale = info[2].As<Napi::Number>().DoubleValue();
|
|
513
|
-
cbIdx = 3;
|
|
514
1103
|
}
|
|
515
1104
|
if (info.Length() >= 5) {
|
|
516
1105
|
maxIterations = info[3].As<Napi::Number>().Int32Value();
|
|
517
|
-
cbIdx = 4;
|
|
518
1106
|
}
|
|
519
1107
|
if (info.Length() >= 6) {
|
|
520
1108
|
terminationEps = info[4].As<Napi::Number>().DoubleValue();
|
|
521
|
-
cbIdx = 5;
|
|
522
1109
|
}
|
|
523
1110
|
if (info.Length() >= 7) {
|
|
524
1111
|
outputFormat = info[5].As<Napi::String>().Utf8Value();
|
|
525
|
-
cbIdx = 6;
|
|
526
1112
|
}
|
|
527
1113
|
if (info.Length() >= 8) {
|
|
528
1114
|
quality = info[6].As<Napi::Number>().Int32Value();
|
|
529
|
-
cbIdx = 7;
|
|
530
1115
|
}
|
|
531
1116
|
if (info.Length() >= 9) {
|
|
532
1117
|
pngOptimize = info[7].As<Napi::Boolean>().Value();
|
|
533
|
-
cbIdx = 8;
|
|
534
1118
|
}
|
|
535
1119
|
if (info.Length() >= 10) {
|
|
536
1120
|
returnMatrix = info[8].As<Napi::Boolean>().Value();
|
|
537
|
-
cbIdx = 9;
|
|
538
1121
|
}
|
|
539
1122
|
if (info.Length() >= 11) {
|
|
540
1123
|
polygon = info[9];
|
|
541
|
-
cbIdx = 10;
|
|
542
1124
|
}
|
|
543
|
-
|
|
1125
|
+
if (info.Length() >= 12) {
|
|
1126
|
+
motionModel = info[10].As<Napi::String>().Utf8Value();
|
|
1127
|
+
}
|
|
1128
|
+
if (info.Length() >= 13) {
|
|
1129
|
+
pipeline = info[11].As<Napi::String>().Utf8Value();
|
|
1130
|
+
}
|
|
1131
|
+
if (info.Length() >= 14) {
|
|
1132
|
+
eccRefine = info[12].As<Napi::String>().Utf8Value();
|
|
1133
|
+
}
|
|
1134
|
+
|
|
544
1135
|
// Create and queue worker
|
|
545
1136
|
ImageAlignWorker* worker = new ImageAlignWorker(callback, referenceImage, targetImage,
|
|
546
1137
|
scale, maxIterations, terminationEps,
|
|
547
|
-
outputFormat, quality, pngOptimize, returnMatrix, polygon
|
|
1138
|
+
outputFormat, quality, pngOptimize, returnMatrix, polygon,
|
|
1139
|
+
motionModel, pipeline, eccRefine);
|
|
548
1140
|
worker->Queue();
|
|
549
|
-
|
|
1141
|
+
|
|
550
1142
|
return env.Undefined();
|
|
551
1143
|
}
|