学习OpenCV范例(二十一)——Keypoints+Knn+findHomography进行目标定位

点击打开链接

本范例的代码主要都是 学习OpenCV——通过KeyPoints进行目标定位这篇博客提供的,然后在它的基础上稍加修改,检测keypoints点的检测器是SURF,获取描述子也是用到SURF来描述,而用到的匹配器是FlannBased,匹配的方式是Knn方式,最后通过findHomography寻找单映射矩阵,perspectiveTransform获得最终的目标,在这个过程中还通过单映射矩阵来进一步去除伪匹配,这里只是贴出代码和代码解析,至于原理还没弄得特别明白,希望接下来可以继续学习,学懂了算法原理再来补充。

1、代码实现

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">#include "stdafx.h"  
  2. #include "opencv2/opencv.hpp"  
  3. #include <vector>    
  4. #include <iostream>    
  5.   
  6. using namespace cv;    
  7. using namespace std;    
  8. Mat src,frameImg;    
  9. int width;    
  10. int height;    
  11. vector<Point> srcCorner(4);    
  12. vector<Point> dstCorner(4);    
  13.   
  14. static bool createDetectorDescriptorMatcher( const string& detectorType, const string& descriptorType, const string& matcherType,    
  15.     Ptr<FeatureDetector>& featureDetector,    
  16.     Ptr<DescriptorExtractor>& descriptorExtractor,    
  17.     Ptr<DescriptorMatcher>& descriptorMatcher )    
  18. {    
  19.     cout << "< Creating feature detector, descriptor extractor and descriptor matcher ..." << endl;    
  20.     if (detectorType=="SIFT"||detectorType=="SURF")    
  21.         initModule_nonfree();    
  22.     featureDetector = FeatureDetector::create( detectorType );    
  23.     descriptorExtractor = DescriptorExtractor::create( descriptorType );    
  24.     descriptorMatcher = DescriptorMatcher::create( matcherType );    
  25.     cout << ">" << endl;    
  26.     bool isCreated = !( featureDetector.empty() || descriptorExtractor.empty() || descriptorMatcher.empty() );    
  27.     if( !isCreated )    
  28.         cout << "Can not create feature detector or descriptor extractor or descriptor matcher of given types." << endl << ">" << endl;    
  29.     return isCreated;    
  30. }    
  31.   
  32.   
  33. bool refineMatchesWithHomography(const std::vector<cv::KeyPoint>& queryKeypoints,      
  34.     const std::vector<cv::KeyPoint>& trainKeypoints,       
  35.     float reprojectionThreshold,      
  36.     std::vector<cv::DMatch>& matches,      
  37.     cv::Mat& homography  )    
  38. {    
  39.     const int minNumberMatchesAllowed = 4;      
  40.     if (matches.size() < minNumberMatchesAllowed)      
  41.         return false;      
  42.     // Prepare data for cv::findHomography      
  43.     std::vector<cv::Point2f> queryPoints(matches.size());      
  44.     std::vector<cv::Point2f> trainPoints(matches.size());      
  45.     for (size_t i = 0; i < matches.size(); i++)      
  46.     {      
  47.         queryPoints[i] = queryKeypoints[matches[i].queryIdx].pt;      
  48.         trainPoints[i] = trainKeypoints[matches[i].trainIdx].pt;      
  49.     }      
  50.     // Find homography matrix and get inliers mask      
  51.     std::vector<unsigned char> inliersMask(matches.size());      
  52.     homography = cv::findHomography(queryPoints,       
  53.         trainPoints,       
  54.         CV_FM_RANSAC,       
  55.         reprojectionThreshold,       
  56.         inliersMask);      
  57.     std::vector<cv::DMatch> inliers;      
  58.     for (size_t i=0; i<inliersMask.size(); i++)      
  59.     {      
  60.         if (inliersMask[i])      
  61.             inliers.push_back(matches[i]);      
  62.     }      
  63.     matches.swap(inliers);    
  64.     Mat homoShow;    
  65.     drawMatches(src,queryKeypoints,frameImg,trainKeypoints,matches,homoShow,Scalar::all(-1),CV_RGB(255,255,255),Mat(),2);         
  66.     imshow("homoShow",homoShow);     
  67.     return matches.size() > minNumberMatchesAllowed;     
  68.   
  69. }    
  70.   
  71.   
  72. bool matchingDescriptor(const vector<KeyPoint>& queryKeyPoints,const vector<KeyPoint>& trainKeyPoints,    
  73.     const Mat& queryDescriptors,const Mat& trainDescriptors,     
  74.     Ptr<DescriptorMatcher>& descriptorMatcher,    
  75.     bool enableRatioTest = true)    
  76. {    
  77.     vector<vector<DMatch>> m_knnMatches;    
  78.     vector<DMatch>m_Matches;    
  79.   
  80.     if (enableRatioTest)    
  81.     {    
  82.         cout<<"KNN Matching"<<endl;    
  83.         const float minRatio = 1.f / 1.5f;    
  84.         descriptorMatcher->knnMatch(queryDescriptors,trainDescriptors,m_knnMatches,2);    
  85.         for (size_t i=0; i<m_knnMatches.size(); i++)    
  86.         {    
  87.             const cv::DMatch& bestMatch = m_knnMatches[i][0];    
  88.             const cv::DMatch& betterMatch = m_knnMatches[i][1];    
  89.             float distanceRatio = bestMatch.distance / betterMatch.distance;    
  90.             if (distanceRatio < minRatio)    
  91.             {    
  92.                 m_Matches.push_back(bestMatch);    
  93.             }    
  94.         }    
  95.   
  96.     }    
  97.     else    
  98.     {    
  99.         cout<<"Cross-Check"<<endl;    
  100.         Ptr<cv::DescriptorMatcher> BFMatcher(new cv::BFMatcher(cv::NORM_HAMMING, true));    
  101.         BFMatcher->match(queryDescriptors,trainDescriptors, m_Matches );    
  102.     }    
  103.     Mat homo;    
  104.     float homographyReprojectionThreshold = 1.0;    
  105.     bool homographyFound = refineMatchesWithHomography(    
  106.         queryKeyPoints,trainKeyPoints,homographyReprojectionThreshold,m_Matches,homo);    
  107.   
  108.     if (!homographyFound)    
  109.         return false;    
  110.     else    
  111.     {    
  112.         if (m_Matches.size()>10)  
  113.         {  
  114.             std::vector<Point2f> obj_corners(4);  
  115.             obj_corners[0] = cvPoint(0,0); obj_corners[1] = cvPoint( src.cols, 0 );  
  116.             obj_corners[2] = cvPoint( src.cols, src.rows ); obj_corners[3] = cvPoint( 0, src.rows );  
  117.             std::vector<Point2f> scene_corners(4);  
  118.             perspectiveTransform( obj_corners, scene_corners, homo);  
  119.             line(frameImg,scene_corners[0],scene_corners[1],CV_RGB(255,0,0),2);    
  120.             line(frameImg,scene_corners[1],scene_corners[2],CV_RGB(255,0,0),2);    
  121.             line(frameImg,scene_corners[2],scene_corners[3],CV_RGB(255,0,0),2);    
  122.             line(frameImg,scene_corners[3],scene_corners[0],CV_RGB(255,0,0),2);    
  123.             return true;    
  124.         }  
  125.         return true;  
  126.     }    
  127.   
  128.   
  129. }    
  130. int main()    
  131. {    
  132.     string filename = "box.png";    
  133.     src = imread(filename,0);    
  134.     width = src.cols;    
  135.     height = src.rows;    
  136.     string detectorType = "SIFT";    
  137.     string descriptorType = "SIFT";    
  138.     string matcherType = "FlannBased";    
  139.   
  140.     Ptr<FeatureDetector> featureDetector;    
  141.     Ptr<DescriptorExtractor> descriptorExtractor;    
  142.     Ptr<DescriptorMatcher> descriptorMatcher;    
  143.     if( !createDetectorDescriptorMatcher( detectorType, descriptorType, matcherType, featureDetector, descriptorExtractor, descriptorMatcher ) )    
  144.     {    
  145.         cout<<"Creat Detector Descriptor Matcher False!"<<endl;    
  146.         return -1;    
  147.     }    
  148.     //Intial: read the pattern img keyPoint    
  149.     vector<KeyPoint> queryKeypoints;    
  150.     Mat queryDescriptor;    
  151.     featureDetector->detect(src,queryKeypoints);    
  152.     descriptorExtractor->compute(src,queryKeypoints,queryDescriptor);    
  153.   
  154.     VideoCapture cap(0); // open the default camera    
  155.     cap.set( CV_CAP_PROP_FRAME_WIDTH,320);  
  156.     cap.set( CV_CAP_PROP_FRAME_HEIGHT,240 );  
  157.     if(!cap.isOpened())  // check if we succeeded    
  158.     {    
  159.         cout<<"Can't Open Camera!"<<endl;    
  160.         return -1;    
  161.     }    
  162.     srcCorner[0] = Point(0,0);    
  163.     srcCorner[1] = Point(width,0);    
  164.     srcCorner[2] = Point(width,height);    
  165.     srcCorner[3] = Point(0,height);    
  166.   
  167.     vector<KeyPoint> trainKeypoints;    
  168.     Mat trainDescriptor;    
  169.   
  170.     Mat frame,grayFrame;  
  171.     char key=0;    
  172.   
  173.     //  frame = imread("box_in_scene.png");    
  174.     while (key!=27)    
  175.     {    
  176.         cap>>frame;    
  177.         if (!frame.empty())  
  178.         {  
  179.             frame.copyTo(frameImg);  
  180.             printf("%d,%d\n",frame.depth(),frame.channels());  
  181.             grayFrame.zeros(frame.rows,frame.cols,CV_8UC1);  
  182.             cvtColor(frame,grayFrame,CV_BGR2GRAY);    
  183.             trainKeypoints.clear();    
  184.             trainDescriptor.setTo(0);    
  185.             featureDetector->detect(grayFrame,trainKeypoints);    
  186.   
  187.             if(trainKeypoints.size()!=0)    
  188.             {    
  189.                 descriptorExtractor->compute(grayFrame,trainKeypoints,trainDescriptor);    
  190.   
  191.                 bool isFound = matchingDescriptor(queryKeypoints,trainKeypoints,queryDescriptor,trainDescriptor,descriptorMatcher);    
  192.                 imshow("foundImg",frameImg);    
  193.   
  194.             }    
  195.         }  
  196.         key = waitKey(1);     
  197.     }    
  198.     cap.release();  
  199.     return 0;  
  200. }  </span>  

2、运行结果


3、用到的类和函数

DescriptorMatcher::knnMatch

功能:对查询集的每个描述子寻找k个最好的匹配子

结构:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"void DescriptorMatcher::knnMatch(const Mat& queryDescriptors, const Mat& trainDescriptors, vector<vector<DMatch>>& matches, int k, const Mat& mask=Mat(), bool compactResult=false ) const</span>  

queryDescriptors :查询描述子集
trainDescriptors :训练描述子集
mask :掩码指定查询和训练描述子集中哪些允许被匹配
matches :每一个matches[i]都有k个或少于k个的匹配子
k :每个查询描述子最好的匹配子数量,如果查询描述子的总数量少于k,则取总数量
compactResult :当masks不为空时,使用此参数,如果compactResult为false,那么matches的容量和查询描述子的数量一样多,如果为true,则matches的容量就没有包含在mask中剔除的匹配点

BFMatcher::BFMatcher

功能:蛮力匹配

结构:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"> BFMatcher::BFMatcher(int normType=NORM_L2, bool crossCheck=false )</span>  

normType :NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2四个中的一个. L1 和L2 规范 对于SIFT和SURF是个更好的选择,而 NORM_HAMMING 应该被用在ORB, BRISK和 BRIEF中, NORM_HAMMING2被用在 ORB 中,当 WTA_K==3 或4 的时候,(详见ORB::ORB描述子)

crossCheck :如果为false,则默认为BFMatcher行为,对每个查找描述子中寻找k个最接近的邻居,如果为true,则是knnMatch() 方法,而k=1,返回一对匹配子,这个方法只返回最接近的距离的一对匹配子,当有足够多的匹配子的时候,这种方法通常能够产生最好的结果和最小的误差。

findHomography

功能:在两个平面之间寻找单映射变换矩阵

结构:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">Mat findHomography(InputArray srcPoints, InputArray dstPoints, int method=0, double ransacReprojThreshold=3, OutputArray mask=noArray() )</span>  

srcPoints :在原平面上点的坐标,CV_32FC2 的矩阵或者vector<Point2f>
dstPoints :在目标平面上点的坐标,CV_32FC2 的矩阵或者 vector<Point2f> .
method –
用于计算单映射矩阵的方法. 
0 - 使用所有的点的常规方法
CV_RANSAC - 基于 RANSAC 的方法

CV_LMEDS - 基于Least-Median 的方法

ransacReprojThreshold:处理一组点对为内部点的最大容忍重投影误差(只在RANSAC方法中使用),其形式为:    如果     \| \texttt{dstPoints} _i -  \texttt{convertPointsHomogeneous} ( \texttt{H} * \texttt{srcPoints} _i) \|  >  \texttt{ransacReprojThreshold}

那么点i则被考虑为内部点,如果srcPoints和dstPoints是以像素为单位,通常把参数设置为1-10范围内 

mask :可选的输出掩码( CV_RANSAC or CV_LMEDS ). 输入的掩码值被忽略. (存储inliers的点)                            

这个函数的作用是在原平面和目标平面之间返回一个单映射矩阵

s_i  \vecthree{x'_i}{y'_i}{1} \sim H  \vecthree{x_i}{y_i}{1}

因此反投影误差\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2是最小的。

如果参数被设置为0,那么这个函数使用所有的点和一个简单的最小二乘算法来计算最初的单应性估计,但是,如果不是所有的点对都完全符合透视变换,那么这个初始的估计会很差,在这种情况下,你可以使用两个robust算法中的一个。 RANSAC 和LMeDS , 使用坐标点对生成了很多不同的随机组合子集(每四对一组),使用这些子集和一个简单的最小二乘法来估计变换矩阵,然后计算出单应性的质量,最好的子集被用来产生初始单应性的估计和掩码。
RANSAC方法几乎可以处理任何异常,但是需要一个阈值, LMeDS 方法不需要任何阈值,但是只有在inliers大于50%时才能计算正确,最后,如果没有outliers和噪音非常小,则可以使用默认的方法。

PerspectiveTransform

功能:向量数组的透视变换

结构:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;">void perspectiveTransform(InputArray src, OutputArray dst, InputArray m)</span>  

src :输入两通道或三通道的浮点数组,每一个元素是一个2D/3D 的矢量转换

dst :输出和src同样的size和type
m :3x3 或者4x4浮点转换矩阵
转换方法为:

(x, y, z)  \rightarrow (x'/w, y'/w, z'/w)

(x', y', z', w') =  \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1  \end{bmatrix}

w =  \fork{w'}{if $w' \ne 0$}{\infty}{otherwise}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值