// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "precomp.hpp" #ifdef HAVE_OPENCV_DNN #include "opencv2/dnn.hpp" #endif namespace cv { LightGlueMatcher::LightGlueMatcher() {} LightGlueMatcher::~LightGlueMatcher() {} void LightGlueMatcher::setImagePairInfo(const std::vector& queryKpts, const std::vector& trainKpts, Size queryImageSize, Size trainImageSize) { Mat qk((int)queryKpts.size(), 2, CV_32F); for (size_t i = 0; i < queryKpts.size(); ++i) { qk.at((int)i, 0) = queryKpts[i].pt.x; qk.at((int)i, 1) = queryKpts[i].pt.y; } Mat tk((int)trainKpts.size(), 2, CV_32F); for (size_t i = 0; i < trainKpts.size(); ++i) { tk.at((int)i, 0) = trainKpts[i].pt.x; tk.at((int)i, 1) = trainKpts[i].pt.y; } setPairInfo(qk, tk, queryImageSize, trainImageSize); } #ifdef HAVE_OPENCV_DNN static void normalizeLightGlueKeypoints(InputArray _keypoints, OutputArray _normalizedKeypoints, Size imageSize, int type, int normalization) { CV_INSTRUMENT_REGION(); Mat keypoints = _keypoints.getMat(); CV_CheckTypeEQ(keypoints.type(), CV_32FC1, "LightGlue keypoints must be an Nx2 CV_32F matrix"); CV_CheckEQ(keypoints.cols, 2, "LightGlue keypoints must be an Nx2 CV_32F matrix"); float sx = 0.0f, sy = 0.0f, ox = 0.0f, oy = 0.0f; if (normalization == LG_NORM_MAX_SIDE) { // LightGlue reference: (p - size / 2) / (max(W, H) / 2), the same scale on both axes. CV_CheckGT(imageSize.width, 0, "LightGlue keypoint normalization requires a valid image width"); CV_CheckGT(imageSize.height, 0, "LightGlue keypoint normalization requires a valid image height"); const float half = 0.5f * (float)std::max(imageSize.width, imageSize.height); sx = sy = 1.0f / half; ox = -0.5f * (float)imageSize.width / half; oy = -0.5f * (float)imageSize.height / half; } else switch (type) { case LG_ALIKED: CV_CheckGT(imageSize.width, 0, "LightGlue keypoint normalization requires a valid image width"); CV_CheckGT(imageSize.height, 0, "LightGlue keypoint normalization requires a valid image height"); sx = 2.0f / (float)imageSize.width; sy = 2.0f / (float)imageSize.height; ox = oy = -1.0f; break; case LG_DISK: CV_CheckGT(imageSize.width, 1, "DISK LightGlue: image width must be >= 2 for [0,1] normalization"); CV_CheckGT(imageSize.height, 1, "DISK LightGlue: image height must be >= 2 for [0,1] normalization"); sx = 1.0f / (float)(imageSize.width - 1); sy = 1.0f / (float)(imageSize.height - 1); break; default: CV_Error(Error::StsBadArg, "Unsupported LightGlue model type"); } _normalizedKeypoints.create(keypoints.rows, 2, CV_32F); Mat normalized = _normalizedKeypoints.getMat(); for (int i = 0; i < keypoints.rows; i++) { const float* src = keypoints.ptr(i); float* dst = normalized.ptr(i); dst[0] = src[0] * sx + ox; dst[1] = src[1] * sy + oy; } } static void normalizeMatcherKeypoints(InputArray keypoints, OutputArray normalizedKeypoints, Size imageSize, int type, int normalization) { if (imageSize.width > 0 && imageSize.height > 0) normalizeLightGlueKeypoints(keypoints, normalizedKeypoints, imageSize, type, normalization); else { // Preserve the existing convention for already-normalized coordinates. Mat kpts = keypoints.getMat(); CV_CheckTypeEQ(kpts.type(), CV_32FC1, "LightGlue keypoints must be an Nx2 CV_32F matrix"); CV_CheckEQ(kpts.cols, 2, "LightGlue keypoints must be an Nx2 CV_32F matrix"); kpts.copyTo(normalizedKeypoints); } } struct LightGluePairContext { Mat queryKeypoints; // Nx2 float (normalized or pixel) Mat trainKeypoints; // Mx2 float Size queryImageSize; Size trainImageSize; bool valid; LightGluePairContext() : valid(false) {} void clear() { queryKeypoints.release(); trainKeypoints.release(); queryImageSize = Size(); trainImageSize = Size(); valid = false; } }; class LightGlueMatcherImpl : public LightGlueMatcher { public: LightGlueMatcherImpl(const String& modelPath, float _scoreThreshold, int backend, int target) { scoreThreshold = _scoreThreshold; net = dnn::readNet(modelPath, "", ""); CV_Assert(!net.empty()); net.setPreferableBackend(backend); net.setPreferableTarget(target); } LightGlueMatcherImpl(const std::vector& modelData, float _scoreThreshold, int backend, int target) { scoreThreshold = _scoreThreshold; net = dnn::readNetFromONNX(modelData); CV_Assert(!net.empty()); net.setPreferableBackend(backend); net.setPreferableTarget(target); } // Private constructor for clone() — shares the already-loaded network LightGlueMatcherImpl(const dnn::Net& _net, float _scoreThreshold) : net(_net), scoreThreshold(_scoreThreshold) {} void setKeypointNormalization(int _normalization) CV_OVERRIDE { if (_normalization != LG_NORM_MODEL && _normalization != LG_NORM_MAX_SIDE) CV_Error(Error::StsBadArg, "Unsupported LightGlue keypoint normalization"); normalization = _normalization; } int getKeypointNormalization() const CV_OVERRIDE { return normalization; } // DescriptorMatcher interface bool isMaskSupported() const CV_OVERRIDE { return false; } // LightGlueMatcher interface void setPairInfo(InputArray queryKpts, InputArray trainKpts, Size queryImageSize = Size(), Size trainImageSize = Size()) CV_OVERRIDE; void clearPairInfo() CV_OVERRIDE; protected: void knnMatchImpl(InputArray queryDescriptors, std::vector>& matches, int k, InputArrayOfArrays masks = noArray(), bool compactResult = false) CV_OVERRIDE; void radiusMatchImpl(InputArray queryDescriptors, std::vector>& matches, float maxDistance, InputArrayOfArrays masks = noArray(), bool compactResult = false) CV_OVERRIDE; void setLightGlueInputs(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, int type); virtual void lightglueMatch(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, std::vector& matches) = 0; bool resolveContext(Mat& queryKpts, Mat& trainKpts, Size& queryImgSize, Size& trainImgSize); // Shared clone() body; pairContext is matcher state, so it is always copied. template Ptr cloneAs(bool emptyTrainData) const { Ptr matcher = makePtr(net, scoreThreshold); matcher->pairContext = pairContext; matcher->normalization = normalization; if (!emptyTrainData) { matcher->trainDescCollection = trainDescCollection; matcher->utrainDescCollection = utrainDescCollection; } return matcher; } dnn::Net net; float scoreThreshold; int normalization = LG_NORM_MODEL; LightGluePairContext pairContext; }; void LightGlueMatcherImpl::setPairInfo(InputArray _queryKpts, InputArray _trainKpts, Size _queryImageSize, Size _trainImageSize) { pairContext.queryKeypoints = _queryKpts.getMat().clone(); pairContext.trainKeypoints = _trainKpts.getMat().clone(); pairContext.queryImageSize = _queryImageSize; pairContext.trainImageSize = _trainImageSize; pairContext.valid = true; } void LightGlueMatcherImpl::clearPairInfo() { pairContext.clear(); } bool LightGlueMatcherImpl::resolveContext(Mat& queryKpts, Mat& trainKpts, Size& queryImgSize, Size& trainImgSize) { if (pairContext.valid) { queryKpts = pairContext.queryKeypoints; trainKpts = pairContext.trainKeypoints; queryImgSize = pairContext.queryImageSize; trainImgSize = pairContext.trainImageSize; return true; } return false; } void LightGlueMatcherImpl::setLightGlueInputs(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, int type) { int N = queryDesc.rows; int M = trainDesc.rows; Mat kpts0, kpts1; normalizeMatcherKeypoints(queryKpts, kpts0, queryImgSize, type, normalization); normalizeMatcherKeypoints(trainKpts, kpts1, trainImgSize, type, normalization); // Prepare blobs: [1, N, 2] and [1, N, D] int descDim = queryDesc.cols; int szK0[] = {1, N, 2}; int szK1[] = {1, M, 2}; int szD0[] = {1, N, descDim}; int szD1[] = {1, M, descDim}; Mat kpts0blob = kpts0.reshape(0, 3, szK0); Mat kpts1blob = kpts1.reshape(0, 3, szK1); Mat desc0blob = queryDesc.reshape(0, 3, szD0); Mat desc1blob = trainDesc.reshape(0, 3, szD1); net.setInput(kpts0blob, "kpts0"); net.setInput(kpts1blob, "kpts1"); net.setInput(desc0blob, "desc0"); net.setInput(desc1blob, "desc1"); } void LightGlueMatcherImpl::knnMatchImpl(InputArray _queryDescriptors, std::vector>& matches, int k, InputArrayOfArrays, bool) { CV_INSTRUMENT_REGION(); if (k != 1) CV_Error(cv::Error::StsBadArg, "LightGlueMatcher only supports k=1"); Mat queryKpts, trainKpts; Size queryImgSize, trainImgSize; if (!resolveContext(queryKpts, trainKpts, queryImgSize, trainImgSize)) { CV_Error(cv::Error::StsBadArg, "LightGlueMatcher: no valid context. Call setPairInfo() before matching."); } CV_Assert(!trainDescCollection.empty()); const Mat& trainDesc = trainDescCollection[0]; Mat queryDesc = _queryDescriptors.getMat(); if (trainDesc.empty()) { matches.assign(queryDesc.rows, std::vector()); clearPairInfo(); return; } std::vector flatMatches; lightglueMatch(queryDesc, trainDesc, queryKpts, trainKpts, queryImgSize, trainImgSize, flatMatches); matches.clear(); matches.resize(queryDesc.rows); for (const auto& m : flatMatches) { matches[m.queryIdx].push_back(m); } clearPairInfo(); } void LightGlueMatcherImpl::radiusMatchImpl(InputArray, std::vector>&, float, InputArrayOfArrays, bool) { CV_Error(cv::Error::StsNotImplemented, "radiusMatch is not supported by LightGlueMatcher. Use match() or knnMatch()."); } // ==================== ALIKED variant ==================== class ALIKEDLightGlueMatcherImpl CV_FINAL : public LightGlueMatcherImpl { public: using LightGlueMatcherImpl::LightGlueMatcherImpl; Ptr clone(bool emptyTrainData) const CV_OVERRIDE { return cloneAs(emptyTrainData); } protected: void lightglueMatch(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, std::vector& matches) CV_OVERRIDE; }; void ALIKEDLightGlueMatcherImpl::lightglueMatch(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, std::vector& matches) { int N = queryDesc.rows; int M = trainDesc.rows; setLightGlueInputs(queryDesc, trainDesc, queryKpts, trainKpts, queryImgSize, trainImgSize, LG_ALIKED); std::vector outNames = {"matches0", "mscores0"}; std::vector outs; net.forward(outs, outNames); CV_Assert(outs.size() == 2); // matches0: [M, 2] int64 - pair indices (kpt0_idx, kpt1_idx) // mscores0: [M] float32 - confidence per pair Mat matchesMat = outs[0]; Mat scoresMat = outs[1]; matches.clear(); int nMatches = matchesMat.rows; matches.reserve(nMatches); for (int i = 0; i < nMatches; i++) { int qIdx = (int)matchesMat.at(i, 0); int tIdx = (int)matchesMat.at(i, 1); if (qIdx >= 0 && tIdx >= 0 && qIdx < N && tIdx < M) { float score = scoresMat.at(i); if (score >= scoreThreshold) { matches.push_back(DMatch(qIdx, tIdx, 1.0f - score)); } } } } // ==================== DISK variant ==================== class DISKLightGlueMatcherImpl CV_FINAL : public LightGlueMatcherImpl { public: using LightGlueMatcherImpl::LightGlueMatcherImpl; Ptr clone(bool emptyTrainData) const CV_OVERRIDE { return cloneAs(emptyTrainData); } protected: void lightglueMatch(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, std::vector& matches) CV_OVERRIDE; }; void DISKLightGlueMatcherImpl::lightglueMatch(const Mat& queryDesc, const Mat& trainDesc, const Mat& queryKpts, const Mat& trainKpts, Size queryImgSize, Size trainImgSize, std::vector& matches) { int N = queryDesc.rows; int M = trainDesc.rows; setLightGlueInputs(queryDesc, trainDesc, queryKpts, trainKpts, queryImgSize, trainImgSize, LG_DISK); // DISK LightGlue has 4 outputs (bidirectional matches + scores) std::vector outNames = {"matches0", "matches1", "mscores0", "mscores1"}; std::vector outs; net.forward(outs, outNames); CV_Assert(outs.size() == 4); // DISK LightGlue outputs: // matches0: [1, N] int64 — for each query kpt i, matched train kpt j (or -1) // matches1: [1, M] int64 — for each train kpt j, matched query kpt i (or -1) // mscores0: [1, N] float — confidence per query kpt // mscores1: [1, M] float — confidence per train kpt // // ORT engine may drop the batch dim, producing [N] / [M] instead of [1, N] / [1, M]. Mat matches0 = outs[0]; // matches0 Mat mscores0 = outs[2]; // mscores0 // Flatten to 1D in case ORT dropped the batch dimension matches0 = matches0.reshape(1, (int)matches0.total()); mscores0 = mscores0.reshape(1, (int)mscores0.total()); CV_Assert(matches0.total() == (size_t)N); CV_Assert(mscores0.total() == (size_t)N); matches.clear(); matches.reserve(N); for (int i = 0; i < N; i++) { int64_t j = matches0.at(i); if (j >= 0 && j < M) { float score = mscores0.at(i); if (score >= scoreThreshold) { matches.push_back(DMatch(i, (int)j, 1.0f - score)); } } } } Ptr LightGlueMatcher::create(const String& modelPath, float scoreThreshold, int backend, int target, int type) { if (type == LG_DISK) return makePtr(modelPath, scoreThreshold, backend, target); else if (type == LG_ALIKED) return makePtr(modelPath, scoreThreshold, backend, target); CV_Error(Error::StsBadArg, "Unsupported LightGlue model type"); } Ptr LightGlueMatcher::create(const std::vector& modelData, float scoreThreshold, int backend, int target, int type) { if (type == LG_DISK) return makePtr(modelData, scoreThreshold, backend, target); else if (type == LG_ALIKED) return makePtr(modelData, scoreThreshold, backend, target); CV_Error(Error::StsBadArg, "Unsupported LightGlue model type"); } #else // !HAVE_OPENCV_DNN Ptr LightGlueMatcher::create(const String& modelPath, float scoreThreshold, int backend, int target, int type) { CV_UNUSED(modelPath); CV_UNUSED(scoreThreshold); CV_UNUSED(backend); CV_UNUSED(target); CV_UNUSED(type); CV_Error(cv::Error::StsNotImplemented, "LightGlueMatcher requires OpenCV built with opencv_dnn module!"); } #endif // HAVE_OPENCV_DNN } // namespace cv