- 操作系統:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 編程語言:C++11
算法描述
cv::detail::BestOf2NearestRangeMatcher 是 OpenCV 庫中用于圖像拼接模塊的一個匹配器類,專門用于尋找兩幅圖像之間的最佳特征點匹配。它是基于“最近鄰與次近鄰距離比”原則來過濾匹配點對的,以提高匹配結果的準確性。這個類特別適用于需要在多張圖片之間進行特征匹配和篩選的應用場景,比如全景圖拼接。
主要特點
- 基于范圍的匹配:此匹配器不僅考慮兩張圖片之間的直接匹配,還會考慮一個范圍內其他圖片間的匹配關系,這對于全景圖像拼接等任務非常有用。
- 最近鄰與次近鄰距離比測試:通過比較每個特征點與其最近和次近鄰居的距離比值來決定是否接受該匹配,這是一種常用的減少誤匹配的技術。
以下是該類的一些成員函數和變量的介紹:
構造函數
BestOf2NearestRangeMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, int num_matches_thresh2 = 6, int range_width = -1);
- try_use_gpu: 是否嘗試使用 GPU 進行加速。
- match_conf: 匹配置信度閾值,用來過濾不可靠的匹配對。
- num_matches_thresh1: 第一個匹配數量閾值,低于此值將不會計算單應性矩陣。
- num_matches_thresh2: 第二個匹配數量閾值,低于此值將不會進行運動估計的細化。
- range_width: 范圍寬度,用于限制匹配搜索的范圍,默認為 -1 表示沒有限制。
成員函數
-
void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info);
執行兩幅圖像間的特征匹配,并填充 MatchesInfo 結構體,包含匹配結果和可能的單應性變換矩陣。 -
void operator()(const std::vector &features, std::vector &pairwise_matches, const UMat &mask);
對一組圖像執行特征匹配,生成所有圖像對之間的匹配信息。
其他成員
- impl_: 實現細節指針,指向具體的匹配器實現(可能是基于 CPU 或者 GPU)。
- is_thread_safe_: 標識是否線程安全。
- num_matches_thresh1_, num_matches_thresh2_: 上述構造函數參數中的兩個匹配數量閾值。
- range_width_: 上述構造函數參數中的范圍寬度。
代碼示例
#include <opencv2/opencv.hpp>
#include <opencv2/stitching/detail/matchers.hpp>using namespace cv;
using namespace cv::detail;int main()
{// 讀取兩幅待匹配的圖像Mat img1 = imread( "/media/dingxin/data/study/OpenCV/sources/images/stich1.png" );Mat img2 = imread( "/media/dingxin/data/study/OpenCV/sources/images/stich2.png" );if ( img1.empty() || img2.empty() ){std::cerr << "無法讀取圖像文件" << std::endl;return -1;}// 初始化特征檢測器和描述符提取器 (這里以ORB為例)Ptr< Feature2D > detector = ORB::create( 500 ); // 提取500個關鍵點// 檢測特征點并計算描述符std::vector< KeyPoint > keypoints1, keypoints2;Mat descriptors1, descriptors2;detector->detectAndCompute( img1, noArray(), keypoints1, descriptors1 );detector->detectAndCompute( img2, noArray(), keypoints2, descriptors2 );// 特征匹配BFMatcher matcher( NORM_HAMMING );std::vector< DMatch > matches;matcher.match( descriptors1, descriptors2, matches );// 繪制匹配結果Mat img_matches;drawMatches( img1, keypoints1, img2, keypoints2, matches, img_matches );// 顯示匹配結果imshow( "Matches", img_matches );waitKey( 0 );return 0;
}