【OpenCV入门教程之十八】OpenCV仿射变换 & SURF特征点描述合辑

本篇文章中,我们一起探讨了OpenCV中仿射变换和SURF特征点描述相关的知识点,主要一起了解OpenCV中仿射变换相关的函数warpAffine和getRotationMatrix2D,SURF算法在OpenCV中进一步的体现与应用。此博文一共有两个配套的麻雀虽小但五脏俱全的示例程序,其经过浅墨详细注释过的代码都在文中贴出,且文章最后提供了综合示例程序的下载。
依然是先看看示例程序截图:










一、仿射变换



1.1 初识仿射变换


仿射变换(Affine Transformation或 Affine Map),又称仿射映射,是指在几何中,一个向量空间进行一次线性变换并接上一个平移,变换为另一个向量空间的过程。它保持了二维图形的“平直性”(即:直线经过变换之后依然是直线)和“平行性”(即:二维图形之间的相对位置关系保持不变,平行线依然是平行线,且直线上点的位置顺序不变)。

一个任意的仿射变换都能表示为乘以一个矩阵(线性变换)接着再加上一个向量(平移)的形式。

那么, 我们能够用仿射变换来表示如下三种常见的变换形式:

  • 旋转,rotation (线性变换)
  • 平移,translation(向量加)
  • 缩放,scale(线性变换)

如果进行更深层次的理解,仿射变换代表的是两幅图之间的一种映射关系。

而我们通常使用2 x 3的矩阵来表示仿射变换。


 

 

考虑到我们要使用矩阵 A 和 B 对二维向量 做变换, 所以也能表示为下列形式:


  或者     


 

即:       

 

 


1. 2 仿射变换的求法


我们知道,仿射变换表示的就是两幅图片之间的一种联系 . 关于这种联系的信息大致可从以下两种场景获得:

  • <1>已知 X和T,而且我们知道他们是有联系的. 接下来我们的工作就是求出矩阵 M
  • <2>已知 M和X,要想求得 T. 我们只要应用算式即可. 对于这种联系的信息可以用矩阵 M 清晰的表达 (即给出明确的2×3矩阵) 或者也可以用两幅图片点之间几何关系来表达。
我们形象地说明一下,因为矩阵 M 联系着两幅图片, 我们就以其表示两图中各三点直接的联系为例。

见下图:


其中,点1, 2 和 3 (在图一中形成一个三角形) 与图二中三个点是一一映射的关系, 且他们仍然形成三角形, 但形状已经和之前不一样了。我们能通过这样两组三点求出仿射变换 (可以选择自己喜欢的点), 接着就可以把仿射变换应用到图像中去。

 

 




1.3 仿射变换相关的函数使用


OpenCV仿射变换相关的函数一般涉及到warpAffine和getRotationMatrix2D这两个:

  • 使用OpenCV函数warpAffine 来实现一些简单的重映射.
  • 使用OpenCV函数getRotationMatrix2D 来获得旋转矩阵。

下面分别对其进行讲解。

 



1.3.1 warpAffine函数详解



warpAffine函数的作用是依据如下式子,对图像做仿射变换。




函数原型如下:

[cpp]   view plain  copy
  1. C++: void warpAffine(InputArray src,OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, intborderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())  

  • 第一个参数,InputArray类型的src,输入图像,即源图像,填Mat类的对象即可。
  • 第二个参数,OutputArray类型的dst,函数调用后的运算结果存在这里,需和源图片有一样的尺寸和类型。
  • 第三个参数,InputArray类型的M,2×3的变换矩阵。
  • 第四个参数,Size类型的dsize,表示输出图像的尺寸。
  • 第五个参数,int类型的flags,插值方法的标识符。此参数有默认值INTER_LINEAR(线性插值),可选的插值方式如下:
    • INTER_NEAREST - 最近邻插值
    • INTER_LINEAR - 线性插值(默认值)
    • INTER_AREA - 区域插值
    • INTER_CUBIC –三次样条插值
    • INTER_LANCZOS4 -Lanczos插值
    • CV_WARP_FILL_OUTLIERS - 填充所有输出图像的象素。如果部分象素落在输入图像的边界外,那么它们的值设定为 fillval.
    • CV_WARP_INVERSE_MAP –表示M为输出图像到输入图像的反变换,即 。因此可以直接用来做象素插值。否则, warpAffine函数从M矩阵得到反变换。
  • 第六个参数,int类型的borderMode,边界像素模式,默认值为BORDER_CONSTANT。
  • 第七个参数,const Scalar&类型的borderValue,在恒定的边界情况下取的值,默认值为Scalar(),即0。

另外提一点,我们的WarpAffine函数与一个叫做cvGetQuadrangleSubPix( )的函数类似,但是不完全相同。 WarpAffine要求输入和输出图像具有同样的数据类型,有更大的资源开销(因此对小图像不太合适)而且输出图像的部分可以保留不变。而 cvGetQuadrangleSubPix 可以精确地从8位图像中提取四边形到浮点数缓存区中,具有比较小的系统开销,而且总是全部改变输出图像的内容。

 

 



1.3.2 getRotationMatrix2D



计算二维旋转变换矩阵。变换会将旋转中心映射到它自身。

[cpp]   view plain  copy
  1. C++: Mat getRotationMatrix2D(Point2fcenter, double angle, double scale)  
  • 第一个参数,Point2f类型的center,表示源图像的旋转中心。
  • 第二个参数,double类型的angle,旋转角度。角度为正值表示向逆时针旋转(坐标原点是左上角)。
  • 第三个参数,double类型的scale,缩放系数。

 

此函数计算以下矩阵:

 

其中:


 

 


1.4 仿射变换相关核心函数在OpenCV中的实现源代码

 


这个部分贴出OpenCV中本节相关函数的源码实现细节,来给想了解实现细节的小伙伴们参考。浅墨暂时不在源码的细节上挖深作详细注释。

 

1.4.1 OpenCV2.X中warpAffine函数源代码


首先,是warpAffine函数的实现源码。
[cpp]   view plain  copy
  1. void cv::warpAffine( InputArray _src,OutputArray _dst,  
  2.                      InputArray _M0, Sizedsize,  
  3.                      int flags, int borderType,const Scalar& borderValue )  
  4. {  
  5.    Mat src = _src.getMat(), M0 = _M0.getMat();  
  6.    _dst.create( dsize.area() == 0 ? src.size() : dsize, src.type() );  
  7.    Mat dst = _dst.getMat();  
  8.    CV_Assert( src.cols > 0 && src.rows > 0 );  
  9.    if( dst.data == src.data )  
  10.        src = src.clone();  
  11.    
  12.    double M[6];  
  13.    Mat matM(2, 3, CV_64F, M);  
  14.    int interpolation = flags & INTER_MAX;  
  15.    if( interpolation == INTER_AREA )  
  16.        interpolation = INTER_LINEAR;  
  17.    
  18.    CV_Assert( (M0.type() == CV_32F || M0.type() == CV_64F) &&M0.rows == 2 && M0.cols == 3 );  
  19.    M0.convertTo(matM, matM.type());  
  20.    
  21. #ifdef HAVE_TEGRA_OPTIMIZATION  
  22.    if( tegra::warpAffine(src, dst, M, flags, borderType, borderValue) )  
  23.        return;  
  24. #endif  
  25.    
  26.    if( !(flags & WARP_INVERSE_MAP) )  
  27.     {  
  28.        double D = M[0]*M[4] - M[1]*M[3];  
  29.        D = D != 0 ? 1./D : 0;  
  30.        double A11 = M[4]*D, A22=M[0]*D;  
  31.        M[0] = A11; M[1] *= -D;  
  32.        M[3] *= -D; M[4] = A22;  
  33.        double b1 = -M[0]*M[2] - M[1]*M[5];  
  34.        double b2 = -M[3]*M[2] - M[4]*M[5];  
  35.        M[2] = b1; M[5] = b2;  
  36.     }  
  37.    
  38.    int x;  
  39.    AutoBuffer<int> _abdelta(dst.cols*2);  
  40.    int* adelta = &_abdelta[0], *bdelta = adelta + dst.cols;  
  41.    const int AB_BITS = MAX(10, (int)INTER_BITS);  
  42.    const int AB_SCALE = 1 << AB_BITS;  
  43. /* 
  44. #if defined (HAVE_IPP) &&(IPP_VERSION_MAJOR >= 7) 
  45.    int depth = src.depth(); 
  46.    int channels = src.channels(); 
  47.     if( ( depth == CV_8U || depth == CV_16U ||depth == CV_32F ) && 
  48.        ( channels == 1 || channels == 3 || channels == 4 ) && 
  49.        ( borderType == cv::BORDER_TRANSPARENT || ( borderType ==cv::BORDER_CONSTANT ) ) ) 
  50.     { 
  51.        int type = src.type(); 
  52.        ippiWarpAffineBackFunc ippFunc = 
  53.            type == CV_8UC1 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_8u_C1R : 
  54.            type == CV_8UC3 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_8u_C3R : 
  55.            type == CV_8UC4 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_8u_C4R : 
  56.            type == CV_16UC1 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_16u_C1R : 
  57.            type == CV_16UC3 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_16u_C3R : 
  58.            type == CV_16UC4 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_16u_C4R : 
  59.            type == CV_32FC1 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_32f_C1R : 
  60.            type == CV_32FC3 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_32f_C3R : 
  61.            type == CV_32FC4 ? (ippiWarpAffineBackFunc)ippiWarpAffineBack_32f_C4R : 
  62.            0; 
  63.        int mode = 
  64.            flags == INTER_LINEAR ? IPPI_INTER_LINEAR : 
  65.            flags == INTER_NEAREST ? IPPI_INTER_NN : 
  66.            flags == INTER_CUBIC ? IPPI_INTER_CUBIC : 
  67.            0; 
  68.        if( mode && ippFunc ) 
  69.        { 
  70.            double coeffs[2][3]; 
  71.            for( int i = 0; i < 2; i++ ) 
  72.            { 
  73.                 for( int j = 0; j < 3; j++ ) 
  74.                 { 
  75.                     coeffs[i][j] =matM.at<double>(i, j); 
  76.                 } 
  77.            } 
  78.            bool ok; 
  79.            Range range(0, dst.rows); 
  80.            IPPwarpAffineInvoker invoker(src, dst, coeffs, mode, borderType,borderValue, ippFunc, &ok); 
  81.            parallel_for_(range, invoker, dst.total()/(double)(1<<16)); 
  82.            if( ok ) 
  83.                 return; 
  84.        } 
  85.     } 
  86. #endif 
  87. */  
  88.    for( x = 0; x < dst.cols; x++ )  
  89.     {  
  90.        adelta[x] = saturate_cast<int>(M[0]*x*AB_SCALE);  
  91.        bdelta[x] = saturate_cast<int>(M[3]*x*AB_SCALE);  
  92.     }  
  93.    
  94.    Range range(0, dst.rows);  
  95.     warpAffineInvokerinvoker(src, dst, interpolation, borderType,  
  96.                               borderValue,adelta, bdelta, M);  
  97.    parallel_for_(range, invoker, dst.total()/(double)(1<<16));  
  98. }  

 



1.4.2 OpenCV2.X中getRotationMatrix2D函数源代码

 


[cpp]   view plain  copy
  1. cv::Mat cv::getRotationMatrix2D( Point2f center,double angle, double scale )  
  2. {  
  3.    angle *= CV_PI/180;  
  4.    double alpha = cos(angle)*scale;  
  5.    double beta = sin(angle)*scale;  
  6.    
  7.    Mat M(2, 3, CV_64F);  
  8.    double* m = (double*)M.data;  
  9.    
  10.    m[0] = alpha;  
  11.    m[1] = beta;  
  12.    m[2] = (1-alpha)*center.x - beta*center.y;  
  13.    m[3] = -beta;  
  14.    m[4] = alpha;  
  15.    m[5] = beta*center.x + (1-alpha)*center.y;  
  16.    
  17.    return M;  
  18. }  





1.5 OpenCV仿射变换示例程序



看完上面的讲解和函数线吗实现,下面是一个以warpAffine和getRotationMatrix2D函数为核心的对图像进行仿射变换的示例程序。

[cpp]   view plain  copy
  1. //-----------------------------------【程序说明】----------------------------------------------    
  2. //      程序名称::《【OpenCV入门教程之十八】OpenCV仿射变换 & SURF特征点描述合辑》 博文配套源码 之 仿射变换  
  3. //      开发所用IDE版本:Visual Studio 2010    
  4. //      开发所用OpenCV版本:   2.4.9    
  5. //      2014年6月 Created by 浅墨    
  6. //      浅墨的微博:@浅墨_毛星云 http://weibo.com/1723155442    
  7. //      浅墨的知乎:http://www.zhihu.com/people/mao-xing-yun    
  8. //      浅墨的豆瓣:http://www.douban.com/people/53426472/    
  9. //----------------------------------------------------------------------------------------------  
  10.   
  11.   
  12. //-----------------------------------【头文件包含部分】---------------------------------------  
  13. //      描述:包含程序所依赖的头文件  
  14. //----------------------------------------------------------------------------------------------  
  15. #include "opencv2/highgui/highgui.hpp"  
  16. #include "opencv2/imgproc/imgproc.hpp"  
  17. #include <iostream>  
  18.   
  19. //-----------------------------------【命名空间声明部分】--------------------------------------  
  20. //      描述:包含程序所使用的命名空间  
  21. //-----------------------------------------------------------------------------------------------  
  22. using namespace cv;  
  23. using namespace std;  
  24.   
  25. //-----------------------------------【宏定义部分】--------------------------------------------   
  26. //      描述:定义一些辅助宏   
  27. //------------------------------------------------------------------------------------------------   
  28. #define WINDOW_NAME1 "【原始图窗口】"                  //为窗口标题定义的宏   
  29. #define WINDOW_NAME2 "【经过Warp后的图像】"        //为窗口标题定义的宏   
  30. #define WINDOW_NAME3 "【经过Warp和Rotate后的图像】"        //为窗口标题定义的宏   
  31.   
  32.   
  33. //-----------------------------------【全局函数声明部分】--------------------------------------  
  34. //      描述:全局函数的声明  
  35. //-----------------------------------------------------------------------------------------------  
  36. static void ShowHelpText( );  
  37.   
  38.   
  39. //-----------------------------------【main( )函数】--------------------------------------------  
  40. //      描述:控制台应用程序的入口函数,我们的程序从这里开始执行  
  41. //-----------------------------------------------------------------------------------------------  
  42. int main(  )  
  43. {  
  44.     //【0】改变console字体颜色  
  45.     system("color 1A");   
  46.   
  47.     //【0】显示欢迎和帮助文字  
  48.     ShowHelpText( );  
  49.   
  50.     //【1】参数准备  
  51.     //定义两组点,代表两个三角形  
  52.     Point2f srcTriangle[3];  
  53.     Point2f dstTriangle[3];  
  54.     //定义一些Mat变量  
  55.     Mat rotMat( 2, 3, CV_32FC1 );  
  56.     Mat warpMat( 2, 3, CV_32FC1 );  
  57.     Mat srcImage, dstImage_warp, dstImage_warp_rotate;  
  58.   
  59.     //【2】加载源图像并作一些初始化  
  60.     srcImage = imread( "1.jpg", 1 );  
  61.     if(!srcImage.data ) { printf("读取图片错误,请确定目录下是否有imread函数指定的图片存在~! \n"); return false; }   
  62.     // 设置目标图像的大小和类型与源图像一致  
  63.     dstImage_warp = Mat::zeros( srcImage.rows, srcImage.cols, srcImage.type() );  
  64.   
  65.     //【3】设置源图像和目标图像上的三组点以计算仿射变换  
  66.     srcTriangle[0] = Point2f( 0,0 );  
  67.     srcTriangle[1] = Point2f( static_cast<float>(srcImage.cols - 1), 0 );  
  68.     srcTriangle[2] = Point2f( 0, static_cast<float>(srcImage.rows - 1 ));  
  69.   
  70.     dstTriangle[0] = Point2f( static_cast<float>(srcImage.cols*0.0), static_cast<float>(srcImage.rows*0.33));  
  71.     dstTriangle[1] = Point2f( static_cast<float>(srcImage.cols*0.65), static_cast<float>(srcImage.rows*0.35));  
  72.     dstTriangle[2] = Point2f( static_cast<float>(srcImage.cols*0.15), static_cast<float>(srcImage.rows*0.6));  
  73.   
  74.     //【4】求得仿射变换  
  75.     warpMat = getAffineTransform( srcTriangle, dstTriangle );  
  76.   
  77.     //【5】对源图像应用刚刚求得的仿射变换  
  78.     warpAffine( srcImage, dstImage_warp, warpMat, dstImage_warp.size() );  
  79.   
  80.     //【6】对图像进行缩放后再旋转  
  81.     // 计算绕图像中点顺时针旋转50度缩放因子为0.6的旋转矩阵  
  82.     Point center = Point( dstImage_warp.cols/2, dstImage_warp.rows/2 );  
  83.     double angle = -30.0;  
  84.     double scale = 0.8;  
  85.     // 通过上面的旋转细节信息求得旋转矩阵  
  86.     rotMat = getRotationMatrix2D( center, angle, scale );  
  87.     // 旋转已缩放后的图像  
  88.     warpAffine( dstImage_warp, dstImage_warp_rotate, rotMat, dstImage_warp.size() );  
  89.   
  90.   
  91.     //【7】显示结果  
  92.     imshow( WINDOW_NAME1, srcImage );  
  93.     imshow( WINDOW_NAME2, dstImage_warp );  
  94.     imshow( WINDOW_NAME3, dstImage_warp_rotate );  
  95.   
  96.     // 等待用户按任意按键退出程序  
  97.     waitKey(0);  
  98.   
  99.     return 0;  
  100. }  
  101.   
  102.   
  103. //-----------------------------------【ShowHelpText( )函数】----------------------------------    
  104. //      描述:输出一些帮助信息    
  105. //----------------------------------------------------------------------------------------------    
  106. static void ShowHelpText()    
  107. {    
  108.     //输出一些帮助信息    
  109.     printf(   "\n\n\n\t欢迎来到【仿射变换】示例程序~\n\n");    
  110.     printf("\t当前使用的OpenCV版本为 OpenCV "CV_VERSION);    
  111.     printf( "\n\n\t\t\t\t\t\t\t\t by浅墨\n\n\n"    
  112.         );    
  113. }    

效果图:






 






二、SURF特征点描述




通过上一篇文章SURF相关内容的讲解,我们已经对SURF算法有了一定的理解。SURF算法为每个检测到的特征定义了位置和尺度,尺度值可用于定义围绕特征点的窗口大小,不论物体的尺度在窗口是什么样的,都将包含相同的视觉信息,这些信息用于表示特征点以使得他们与众不同。

在特征匹配中,特征描述子通常是用于N维向量,在光照不变以及少许透视变形的情况下很理想。另外,优质的描述子可以通过简单的距离测量进行比较,比如欧氏距离。因此,他们在特征匹配算法中,用处是很大的。

 

在OpenCV中,使用SURF进行特征点描述主要是drawMatches方法和BruteForceMatcher类的运用,让我们一起来认识他们。

 


2.1 drawMatches函数详解


drawMatches用于绘制出相匹配的两个图像的关键点,它有如下两个版本的C++函数原型:


[cpp]   view plain  copy
  1. C++: void drawMatches(const Mat& img1,  
  2. constvector<KeyPoint>& keypoints1,  
  3.  const Mat& img2,  
  4.  constvector<KeyPoint>& keypoints2,  
  5.  constvector<DMatch>& matches1to2,  
  6.  Mat& outImg,  
  7.  const Scalar&matchColor=Scalar::all(-1),  
  8.  const Scalar&singlePointColor=Scalar::all(-1),  
  9.  const vector<char>&matchesMask=vector<char>(),  
  10.  intflags=DrawMatchesFlags::DEFAULT )  

[cpp]   view plain  copy
  1. C++: void drawMatches(const Mat& img1,  
  2.  constvector<KeyPoint>& keypoints1,  
  3.  const Mat& img2,  
  4.  constvector<KeyPoint>& keypoints2,  
  5.  const vector<vector<DMatch>>&matches1to2,  
  6.  Mat& outImg,  
  7.  const Scalar&matchColor=Scalar::all(-1),  
  8.  const Scalar&singlePointColor=Scalar::all(-1),  
  9.  constvector<vector<char>>& matchesMask=vector<vector<char>>(),  
  10.  intflags=DrawMatchesFlags::DEFAULT )  


除了第五个参数matches1to2和第九个参数matchesMask有细微的差别以外,两个版本的基本上相同。


  • 第一个参数,const Mat&类型的img1,第一幅源图像。
  • 第二个参数,const vector<KeyPoint>&类型的keypoints1,根据第一幅源图像得到的特征点,它是一个输出参数。
  • 第三个参数,const Mat&类型的img2,第二幅源图像。
  • 第四个参数,const vector<KeyPoint>&类型的keypoints2,根据第二幅源图像得到的特征点,它是一个输出参数。
  • 第五个参数,matches1to2,第一幅图像到第二幅图像的匹配点,即表示每一个图1中的特征点都在图2中有一一对应的点、
  • 第六个参数,Mat&类型的outImg,输出图像,其内容取决于第五个参数标识符falgs。
  • 第七个参数,const Scalar&类型的matchColor,匹配的输出颜色,即线和关键点的颜色。它有默认值Scalar::all(-1),表示颜色是随机生成的。
  • 第八个参数,const Scalar&类型的singlePointColor,单一特征点的颜色,它也有表示随机生成颜色的默认值Scalar::all(-1)。
  • 第九个参数,matchesMask,确定哪些匹配是会绘制出来的掩膜,如果掩膜为空,表示所有匹配都进行绘制。
  • 第十个参数,int类型的flags,特征绘制的标识符,有默认值DrawMatchesFlags::DEFAULT。可以在如下这个DrawMatchesFlags结构体中选取值:
[cpp]   view plain  copy
  1. struct DrawMatchesFlags  
  2. {  
  3.    enum  
  4.     {  
  5.        DEFAULT = 0, // Output image matrix will be created (Mat::create),  
  6.                      // i.e. existing memory ofoutput image may be reused.  
  7.                      // Two source images,matches, and single keypoints  
  8.                      // will be drawn.  
  9.                      // For each keypoint, only the center pointwill be  
  10.                      // drawn (without a circlearound the keypoint with the  
  11.                      // keypoint size andorientation).  
  12.        DRAW_OVER_OUTIMG = 1, // Output image matrix will not be  
  13.                        // created (usingMat::create). Matches will be drawn  
  14.                        // on existing contentof output image.  
  15.        NOT_DRAW_SINGLE_POINTS = 2, // Single keypoints will not be drawn.  
  16.        DRAW_RICH_KEYPOINTS = 4 // For each keypoint, the circle around  
  17.                        // keypoint withkeypoint size and orientation will  
  18.                        // be drawn.  
  19.    };  
  20. };  

 



2.2 OpenCV2.X中drawMatches函数源代码



在D:\Program Files(x86)\opencv\sources\modules\features2d\src\draw.cpp路径下,有drawMatches函数两个版本的源码。在这里贴出OpenCV中本其源码实现细节,来给想了解实现细节的小伙伴们参考。

 

[cpp]   view plain  copy
  1. void drawMatches( const Mat& img1,const vector<KeyPoint>& keypoints1,  
  2.                   const Mat& img2, constvector<KeyPoint>& keypoints2,  
  3.                   constvector<DMatch>& matches1to2, Mat& outImg,  
  4.                   const Scalar& matchColor,const Scalar& singlePointColor,  
  5.                   const vector<char>&matchesMask, int flags )  
  6. {  
  7.    if( !matchesMask.empty() && matchesMask.size() !=matches1to2.size() )  
  8.        CV_Error( CV_StsBadSize, "matchesMask must have the same size asmatches1to2" );  
  9.    
  10.    Mat outImg1, outImg2;  
  11.    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,  
  12.                                  outImg, outImg1,outImg2, singlePointColor, flags );  
  13.    
  14.    // draw matches  
  15.    forsize_t m = 0; m < matches1to2.size(); m++ )  
  16.     {  
  17.        if( matchesMask.empty() || matchesMask[m] )  
  18.        {  
  19.            int i1 = matches1to2[m].queryIdx;  
  20.            int i2 = matches1to2[m].trainIdx;  
  21.            CV_Assert(i1 >= 0 && i1 <static_cast<int>(keypoints1.size()));  
  22.            CV_Assert(i2 >= 0 && i2 <static_cast<int>(keypoints2.size()));  
  23.    
  24.            const KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];  
  25.            _drawMatch( outImg, outImg1, outImg2, kp1, kp2, matchColor, flags );  
  26.        }  
  27.     }  
  28. }  
  29.    
  30. void drawMatches( const Mat& img1,const vector<KeyPoint>& keypoints1,  
  31.                   const Mat& img2, constvector<KeyPoint>& keypoints2,  
  32.                   constvector<vector<DMatch> >& matches1to2, Mat& outImg,  
  33.                   const Scalar& matchColor,const Scalar& singlePointColor,  
  34.                   constvector<vector<char> >& matchesMask, int flags )  
  35. {  
  36.    if( !matchesMask.empty() && matchesMask.size() !=matches1to2.size() )  
  37.        CV_Error( CV_StsBadSize, "matchesMask must have the same size asmatches1to2" );  
  38.    
  39.    Mat outImg1, outImg2;  
  40.    _prepareImgAndDrawKeypoints( img1, keypoints1, img2, keypoints2,  
  41.                                  outImg, outImg1, outImg2,singlePointColor, flags );  
  42.    
  43.    // draw matches  
  44.    forsize_t i = 0; i < matches1to2.size(); i++ )  
  45.     {  
  46.        forsize_t j = 0; j < matches1to2[i].size(); j++ )  
  47.        {  
  48.            int i1 = matches1to2[i][j].queryIdx;  
  49.            int i2 = matches1to2[i][j].trainIdx;  
  50.            if( matchesMask.empty() || matchesMask[i][j] )  
  51.            {  
  52.                 const KeyPoint &kp1 =keypoints1[i1], &kp2 = keypoints2[i2];  
  53.                _drawMatch( outImg,outImg1, outImg2, kp1, kp2, matchColor, flags );  
  54.            }  
  55.        }  
  56.     }  
  57. }  
  58. }  


BruteForceMatcher类源码分析

 

接下来,我们看看本文示例程序中会用到的BruteForceMatcher类的源码分析。在D:\Program Files(x86)\opencv\sources\modules\legacy\include\opencv2\legacy\legacy.hpp路径下,可以找到BruteForceMatcher类的定义。

 

[cpp]   view plain  copy
  1. template<class Distance>  
  2. class CV_EXPORTS BruteForceMatcher : publicBFMatcher  
  3. {  
  4. public:  
  5.    BruteForceMatcher( Distance d = Distance() ) : BFMatcher(Distance::normType,false) {(void)d;}  
  6.    virtual ~BruteForceMatcher() {}  
  7. };  


其公共继承自BFMatcher类。而BFMatcher类位于D:\Program Files(x86)\opencv\sources\modules\features2d\include\opencv2\features2d\features2d.hpp

路径之下,我们一起看看其代码:

 

[cpp]   view plain  copy
  1. /* 
  2.  *Brute-force descriptor matcher. 
  3.  * 
  4.  *For each descriptor in the first set, this matcher finds the closest 
  5.  *descriptor in the second set by trying each one. 
  6.  * 
  7.  *For efficiency, BruteForceMatcher is templated on the distance metric. 
  8.  *For float descriptors, a common choice would be cv::L2<float>. 
  9.  */  
  10. class CV_EXPORTS_W BFMatcher : publicDescriptorMatcher  
  11. {  
  12. public:  
  13.    CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false );  
  14.    virtual ~BFMatcher() {}  
  15.    
  16.    virtual bool isMaskSupported() const { return true; }  
  17.    
  18.     virtual Ptr<DescriptorMatcher> clone(bool emptyTrainData=false ) const;  
  19.    
  20.    AlgorithmInfo* info() const;  
  21. protected:  
  22.    virtual void knnMatchImpl( const Mat& queryDescriptors,vector<vector<DMatch> >& matches, int k,  
  23.           const vector<Mat>& masks=vector<Mat>(), boolcompactResult=false );  
  24.    virtual void radiusMatchImpl( const Mat& queryDescriptors,vector<vector<DMatch> >& matches, float maxDistance,  
  25.           const vector<Mat>& masks=vector<Mat>(), boolcompactResult=false );  
  26.    
  27.    int normType;  
  28.    bool crossCheck;  
  29. };  


发现公共其继承自DescriptorMatcher类,再次进行溯源,在D:\Program Files(x86)\opencv\sources\modules\features2d\include\opencv2\features2d\features2d.hpp路径下找到DescriptorMatcher类的定义。

 

[cpp]   view plain  copy
  1. /****************************************************************************************\ 
  2. *                                 DescriptorMatcher                                     * 
  3. \****************************************************************************************/  
  4. /* 
  5.  *Abstract base class for matching two sets of descriptors. 
  6.  */  
  7. class CV_EXPORTS_W DescriptorMatcher :public Algorithm  
  8. {  
  9. public:  
  10.    virtual ~DescriptorMatcher();  
  11.    
  12.    /* 
  13.     * Add descriptors to train descriptor collection. 
  14.     * descriptors      Descriptors toadd. Each descriptors[i] is a descriptors set from one image. 
  15.     */  
  16.    CV_WRAP virtual void add( const vector<Mat>& descriptors );  
  17.    /* 
  18.     * Get train descriptors collection. 
  19.     */  
  20.    CV_WRAP const vector<Mat>& getTrainDescriptors() const;  
  21.    /* 
  22.     * Clear train descriptors collection. 
  23.     */  
  24.    CV_WRAP virtual void clear();  
  25.    
  26.    /* 
  27.     * Return true if there are not train descriptors in collection. 
  28.     */  
  29.    CV_WRAP virtual bool empty() const;  
  30.    /* 
  31.     * Return true if the matcher supports mask in match methods. 
  32.     */  
  33.    CV_WRAP virtual bool isMaskSupported() const = 0;  
  34.    
  35.    /* 
  36.     * Train matcher (e.g. train flann index). 
  37.     * In all methods to match the method train() is run every time beforematching. 
  38.     * Some descriptor matchers (e.g. BruteForceMatcher) have emptyimplementation 
  39.     * of this method, other matchers really train their inner structures 
  40.     * (e.g. FlannBasedMatcher trains flann::Index). So nonemptyimplementation 
  41.     * of train() should check the class object state and dotraing/retraining 
  42.     * only if the state requires that (e.g. FlannBasedMatcher trainsflann::Index 
  43.     * if it has not trained yet or if new descriptors have been added to thetrain 
  44.     * collection). 
  45.     */  
  46.    CV_WRAP virtual void train();  
  47.    /* 
  48.     * Group of methods to match descriptors from image pair. 
  49.     * Method train() is run in this methods. 
  50.     */  
  51.    // Find one best match for each query descriptor (if mask is empty).  
  52.    CV_WRAP void match( const Mat& queryDescriptors, const Mat&trainDescriptors,  
  53.                 CV_OUT vector<DMatch>&matches, const Mat& mask=Mat() ) const;  
  54.    // Find k best matches for each query descriptor (in increasing order ofdistances).  
  55.    // compactResult is used when mask is not empty. If compactResult isfalse matches  
  56.    // vector will have the same size as queryDescriptors rows. IfcompactResult is true  
  57.    // matches vector will not contain matches for fully masked out querydescriptors.  
  58.    CV_WRAP void knnMatch( const Mat& queryDescriptors, const Mat&trainDescriptors,  
  59.                    CV_OUTvector<vector<DMatch> >& matches, int k,  
  60.                    const Mat& mask=Mat(),bool compactResult=false ) const;  
  61.    // Find best matches for each query descriptor which have distance lessthan  
  62.    // maxDistance (in increasing order of distances).  
  63.    void radiusMatch( const Mat& queryDescriptors, const Mat&trainDescriptors,  
  64.                      vector<vector<DMatch> >& matches, float maxDistance,  
  65.                       const Mat&mask=Mat(), bool compactResult=false ) const;  
  66.    /* 
  67.     * Group of methods to match descriptors from one image to image set. 
  68.     * See description of similar methods for matching image pair above. 
  69.     */  
  70.    CV_WRAP void match( const Mat& queryDescriptors, CV_OUTvector<DMatch>& matches,  
  71.                constvector<Mat>& masks=vector<Mat>() );  
  72.    CV_WRAP void knnMatch( const Mat& queryDescriptors, CV_OUTvector<vector<DMatch> >& matches, int k,  
  73.           const vector<Mat>& masks=vector<Mat>(), boolcompactResult=false );  
  74.    void radiusMatch( const Mat& queryDescriptors,vector<vector<DMatch> >& matches, float maxDistance,  
  75.                    const vector<Mat>&masks=vector<Mat>(), bool compactResult=false );  
  76.    
  77.    // Reads matcher object from a file node  
  78.    virtual void read( const FileNode& );  
  79.    // Writes matcher object to a file storage  
  80.    virtual void write( FileStorage& ) const;  
  81.    
  82.    // Clone the matcher. If emptyTrainData is false the method create deepcopy of the object, i.e. copies  
  83.    // both parameters and train data. If emptyTrainData is true the methodcreate object copy with current parameters  
  84.    // but with empty train data.  
  85.    virtual Ptr<DescriptorMatcher> clone( bool emptyTrainData=false )const = 0;  
  86.    
  87.    CV_WRAP static Ptr<DescriptorMatcher> create( const string&descriptorMatcherType );  
  88. protected:  
  89.    /* 
  90.     * Class to work with descriptors from several images as with one mergedmatrix. 
  91.     * It is used e.g. in FlannBasedMatcher. 
  92.     */  
  93.    class CV_EXPORTS DescriptorCollection  
  94.     {  
  95.    public:  
  96.         DescriptorCollection();  
  97.        DescriptorCollection( const DescriptorCollection& collection );  
  98.        virtual ~DescriptorCollection();  
  99.    
  100.        // Vector of matrices "descriptors" will be merged to onematrix "mergedDescriptors" here.  
  101.        void set( const vector<Mat>& descriptors );  
  102.        virtual void clear();  
  103.    
  104.        const Mat& getDescriptors() const;  
  105.        const Mat getDescriptor( int imgIdx, int localDescIdx ) const;  
  106.        const Mat getDescriptor( int globalDescIdx ) const;  
  107.        void getLocalIdx( int globalDescIdx, int& imgIdx, int&localDescIdx ) const;  
  108.    
  109.        int size() const;  
  110.    
  111.    protected:  
  112.        Mat mergedDescriptors;  
  113.        vector<int> startIdxs;  
  114.    };  
  115.    
  116.    // In fact the matching is implemented only by the following two methods.These methods suppose  
  117.    // that the class object has been trained already. Public match methodscall these methods  
  118.    // after calling train().  
  119.    virtual void knnMatchImpl( const Mat& queryDescriptors,vector<vector<DMatch> >& matches, int k,  
  120.            const vector<Mat>&masks=vector<Mat>(), bool compactResult=false ) = 0;  
  121.    virtual void radiusMatchImpl( const Mat& queryDescriptors,vector<vector<DMatch> >& matches, float maxDistance,  
  122.           const vector<Mat>& masks=vector<Mat>(), bool compactResult=false) = 0;  
  123.    
  124.    static bool isPossibleMatch( const Mat& mask, int queryIdx, inttrainIdx );  
  125.    static bool isMaskedOut( const vector<Mat>& masks, intqueryIdx );  
  126.    
  127.    static Mat clone_op( Mat m ) { return m.clone(); }  
  128.    void checkMasks( const vector<Mat>& masks, intqueryDescriptorsCount ) const;  
  129.    
  130.    // Collection of descriptors from train images.  
  131.    vector<Mat> trainDescCollection;  
  132. };  

可以发现,DescriptorMatcher类和之前我们讲到FeatureDetector 类和DescriptorExtractor类一样,都是继承自他们“德高望重的祖先”Algorithm基类的。

而我们用BruteForceMatcher类时用到最多的match方法,是它从DescriptorMatcher类那里的“拿来主义”。定义如下:


[cpp]   view plain  copy
  1. //为各种描述符找到一个最佳的匹配(若掩膜为空)  
  2. CV_WRAP void match( const Mat& queryDescriptors, const Mat&trainDescriptors,  
  3.              CV_OUTvector<DMatch>& matches, const Mat& mask=Mat() ) const;  






2.3 SURF特征匹配示例程序



这个示例程序中,我们利用SurfDescriptorExtractor类进行特征向量的相关计算。

程序利用了SURF特征的特征描述办法,其操作封装在类SurfFeatureDetector中,利用类内的detect函数可以检测出SURF特征的关键点,保存在vector容器中。第二步利用SurfDescriptorExtractor类进行特征向量的相关计算。将之前的vector变量变成向量矩阵形式保存在Mat中。最后强行匹配两幅图像的特征向量,利用了类BruteForceMatcher中的函数match。

程序的核心思想是:

  • 使用 DescriptorExtractor 接口来寻找关键点对应的特征向量。
  • 使用 SurfDescriptorExtractor 以及它的函数 compute 来完成特定的计算。
  • 使用 BruteForceMatcher 来匹配特征向量。
  • 使用函数 drawMatches 来绘制检测到的匹配点。

关键点讲解:OpenCV2引入了一个通用类,用于提取不同的特征点描述子,计算如下:

 

[cpp]   view plain  copy
  1. //【4】计算描述子(特征向量)  
  2.        SurfDescriptorExtractorextractor;  
  3.        Matdescriptors1, descriptors2;  
  4.        extractor.compute(srcImage1, keyPoint1, descriptors1 );  
  5.        extractor.compute(srcImage2, keyPoints2, descriptors2 );  

 

这里的结果为一个Mat矩阵,它的行数与特征点向量中元素个数是一致的。每行都是一个N维描述子的向量,比如SURF算法默认的描述子维度为64,该向量描绘了特征点周围的强度样式。两个特征点越相似,他们的特征向量也越靠近。这些描述子在图像匹配中尤其有用,如我们想匹配同一个场景中的两幅图像。首先,我们检测每幅图像中的特征,然后提取他们的描述子。第一幅图像中的每一个特征描述子向量都会与第二幅图中的描述子进行比较,得分最高的一对描述子,也就是两个向量的距离最近)将被视为那个特征的最佳匹配。该过程对于第一幅图像中的所有特征进行重复,这便是BruteForceMatcher中实行的最基本的策略。相关代码如下:

 

[cpp]   view plain  copy
  1. //【5】使用BruteForce进行匹配  
  2. //实例化一个匹配器  
  3. BruteForceMatcher<L2<float> > matcher;  
  4. std::vector<DMatch > matches;  
  5. //匹配两幅图中的描述子(descriptors)  
  6. matcher.match(descriptors1, descriptors2, matches );  


BruteForceMatcher是由DescriptorMatcher派生出来的一个类,而DescriptorMatcher定义了不同的匹配策略的共同接口。调用match方法后,在其第三个参数输出一个cv::DMatch向量。于是我们定义一个std::vector<DMatch>类型的matches。

调用match方法之后,我们便可以使用drawMatches方法对匹配到的点进行绘制,并最终显示出来。相关代码如下:

 

[cpp]   view plain  copy
  1. //【6】绘制从两个图像中匹配出的关键点  
  2. MatimgMatches;  
  3. drawMatches(srcImage1, keyPoint1, srcImage2, keyPoints2, matches, imgMatches );//进行绘制  
  4. //【7】显示效果图  
  5. imshow("匹配图", imgMatches );  

 

核心部分讲解完毕,下面我们一起来看看详细注释的示例程序的完全体。

[cpp]   view plain  copy
  1. //-----------------------------------【程序说明】----------------------------------------------    
  2. //      程序名称::《【OpenCV入门教程之十八】OpenCV仿射变换 & SURF特征点描述合辑》 博文配套源码 之 仿射变换  
  3. //      开发所用IDE版本:Visual Studio 2010    
  4. //      开发所用OpenCV版本:   2.4.9    
  5. //      2014年6月 Created by 浅墨    
  6. //      浅墨的微博:@浅墨_毛星云 http://weibo.com/1723155442    
  7. //      浅墨的知乎:http://www.zhihu.com/people/mao-xing-yun    
  8. //      浅墨的豆瓣:http://www.douban.com/people/53426472/    
  9. //----------------------------------------------------------------------------------------------  
  10.   
  11. //-----------------------------------【头文件包含部分】---------------------------------------  
  12. //      描述:包含程序所依赖的头文件  
  13. //----------------------------------------------------------------------------------------------  
  14. #include "opencv2/core/core.hpp"  
  15. #include "opencv2/features2d/features2d.hpp"  
  16. #include "opencv2/highgui/highgui.hpp"  
  17. #include <opencv2/nonfree/nonfree.hpp>  
  18. #include<opencv2/legacy/legacy.hpp>  
  19. #include <iostream>  
  20.   
  21.   
  22. //-----------------------------------【命名空间声明部分】--------------------------------------  
  23. //      描述:包含程序所使用的命名空间  
  24. //-----------------------------------------------------------------------------------------------  
  25. using namespace cv;  
  26. using namespace std;  
  27.   
  28. //-----------------------------------【全局函数声明部分】--------------------------------------  
  29. //      描述:全局函数的声明  
  30. //-----------------------------------------------------------------------------------------------  
  31. static void ShowHelpText( );//输出帮助文字  
  32.   
  33.   
  34. //-----------------------------------【main( )函数】--------------------------------------------  
  35. //      描述:控制台应用程序的入口函数,我们的程序从这里开始执行  
  36. //-----------------------------------------------------------------------------------------------  
  37. int main(  )  
  38. {  
  39.     //【0】改变console字体颜色  
  40.     system("color 1A");   
  41.   
  42.     //【0】显示欢迎和帮助文字  
  43.     ShowHelpText( );  
  44.   
  45.     //【1】载入素材图  
  46.     Mat srcImage1 = imread("1.jpg",1);  
  47.     Mat srcImage2 = imread("2.jpg",1);  
  48.     if( !srcImage1.data || !srcImage2.data )  
  49.     { printf("读取图片错误,请确定目录下是否有imread函数指定的图片存在~! \n"); return false; }    
  50.   
  51.     //【2】使用SURF算子检测关键点  
  52.     int minHessian = 700;//SURF算法中的hessian阈值  
  53.     SurfFeatureDetector detector( minHessian );//定义一个SurfFeatureDetector(SURF) 特征检测类对象    
  54.     std::vector<KeyPoint> keyPoint1, keyPoints2;//vector模板类,存放任意类型的动态数组  
  55.   
  56.     //【3】调用detect函数检测出SURF特征关键点,保存在vector容器中  
  57.     detector.detect( srcImage1, keyPoint1 );  
  58.     detector.detect( srcImage2, keyPoints2 );  
  59.   
  60.     //【4】计算描述符(特征向量)  
  61.     SurfDescriptorExtractor extractor;  
  62.     Mat descriptors1, descriptors2;  
  63.     extractor.compute( srcImage1, keyPoint1, descriptors1 );  
  64.     extractor.compute( srcImage2, keyPoints2, descriptors2 );  
  65.   
  66.     //【5】使用BruteForce进行匹配  
  67.     // 实例化一个匹配器  
  68.     BruteForceMatcher< L2<float> > matcher;  
  69.     std::vector< DMatch > matches;  
  70.     //匹配两幅图中的描述子(descriptors)  
  71.     matcher.match( descriptors1, descriptors2, matches );  
  72.   
  73.     //【6】绘制从两个图像中匹配出的关键点  
  74.     Mat imgMatches;  
  75.     drawMatches( srcImage1, keyPoint1, srcImage2, keyPoints2, matches, imgMatches );//进行绘制  
  76.   
  77.     //【7】显示效果图  
  78.     imshow("匹配图", imgMatches );  
  79.   
  80.     waitKey(0);  
  81.     return 0;  
  82. }  
  83.   
  84. //-----------------------------------【ShowHelpText( )函数】----------------------------------    
  85. //      描述:输出一些帮助信息    
  86. //----------------------------------------------------------------------------------------------    
  87. static void ShowHelpText()    
  88. {    
  89.     //输出一些帮助信息    
  90.     printf(  "\n\n\n\t欢迎来到【SURF特征描述】示例程序~\n\n");    
  91.     printf("\t当前使用的OpenCV版本为 OpenCV "CV_VERSION  
  92.         "\n\n\t\t\t\t\t\t\t\t by浅墨\n\n\n"  );    
  93. }    

看看运行效果图。

两幅原始图:

 

效果图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值