0


SIFT算法详解(附有完整代码)

说明:本文旨在给出 SIFT 算法的具体实现,而在 SIFT 详解上只是做出简单介绍,在这里可以给大家推荐一篇好文:https://blog.csdn.net/zddblog/article/details/7521424;结合这篇文章和下文的具体代码实现,我相信你能很快掌握并运用 SIFT 算法,加油哦!!!如有疑问大家可以一起讨论学习!!!

一、SIFT算法简介

  1. SIFT,即尺度不变特征变换(Scale-invariant feature transformSIFT),是用于图像处理领域的一种描述。这种描述具有尺度不变性,可在图像中检测出关键点,是一种局部特征描述子。该方法于1999年由David Lowe 首先发表于计算机视觉国际会议(International Conference on Computer VisionICCV),2004年再次经David Lowe整理完善后发表于International journal of computer visionIJCV)。截止20148月,该论文单篇被引次数达25000余次。

1、SIFT算法的特点

(1) SIFT特征是图像的局部特征,其对旋转、尺度缩放、亮度变化保持不变性,对视角变化、仿射变换、噪声也保持一定程度的稳定性;

(2)独特性(Distinctiveness)好,信息量丰富,适用于在海量特征数据库中进行快速、准确的匹配;

(3)多量性,即使少数的几个物体也可以产生大量的SIFT特征向量;

(4)高速性,经优化的SIFT匹配算法甚至可以达到实时的要求;

(5)可扩展性,可以很方便的与其他形式的特征向量进行联合。

2、SIFT算法可以解决的问题

  1. 目标的自身状态、场景所处的环境和成像器材的成像特性等因素影响图像配准/目标识别跟踪的性能。而SIFT算法在一定程度上可解决:

(1)目标的旋转、缩放、平移(RST)

(2)图像仿射/投影变换(视点viewpoint)

(3)光照影响(illumination)

(4)目标遮挡(occlusion)

(5)杂物场景(clutter)

(6)噪声

  1. SIFT算法的实质是在不同的尺度空间上查找关键点(特征点),并计算出关键点的方向。SIFT所查找到的关键点是一些十分突出,不会因光照,仿射变换和噪音等因素而变化的点,如角点、边缘点、暗区的亮点及亮区的暗点等。

二、SIFT算法分为如下四步

1. 尺度空间极值检测

  1. 搜索所有尺度上的图像位置。通过高斯微分函数来识别潜在的对于尺度和旋转不变的兴趣点。

2. 关键点定位

  1. 在每个候选的位置上,通过一个拟合精细的模型来确定位置和尺度。关键点的选择依据于它们的稳定程度。

3. 方向确定

  1. 基于图像局部的梯度方向,分配给每个关键点位置一个或多个方向。所有后面的对图像数据的操作都相对于关键点的方向、尺度和位置进行变换,从而提供对于这些变换的不变性。

4. 关键点描述

  1. 在每个关键点周围的邻域内,在选定的尺度上测量图像局部的梯度。这些梯度被变换成一种表示,这种表示允许比较大的局部形状的变形和光照变化。

三、SIFT具体实现

说明:代码实现主要有七个源文件,我和大家一样有时候下载了好几个资源然而没有一个能用的,导致最后都不知道要下载哪一个、是否要下载;所以这里直接把代码贴出来了!

1、mySift.h

  1. #pragma once //防止头文件重复包含和下面作用一样
  2. #include<iostream>
  3. #include<vector>
  4. #include<opencv2\core\core.hpp>
  5. #include<opencv2\features2d\features2d.hpp>
  6. using namespace std;
  7. using namespace cv;
  8. /*************************定义常量*****************************/
  9. //高斯核大小和标准差关系,size=2*(GAUSS_KERNEL_RATIO*sigma)+1,经常设置GAUSS_KERNEL_RATIO=2-3之间
  10. const double GAUSS_KERNEL_RATIO = 3;
  11. const int MAX_OCTAVES = 8; //金字塔最大组数
  12. const float CONTR_THR = 0.04f; //默认是的对比度阈值(D(x))
  13. const float CURV_THR = 10.0f; //关键点主曲率阈值
  14. const float INIT_SIGMA = 0.5f; //输入图像的初始尺度
  15. const int IMG_BORDER = 2; //图像边界忽略的宽度,也可以改为 1
  16. const int MAX_INTERP_STEPS = 5; //关键点精确插值次数
  17. const int ORI_HIST_BINS = 36; //计算特征点方向直方图的BINS个数
  18. const float ORI_SIG_FCTR = 1.5f; //计算特征点主方向时候,高斯窗口的标准差因子
  19. const float ORI_RADIUS = 3 * ORI_SIG_FCTR; //计算特征点主方向时,窗口半径因子
  20. const float ORI_PEAK_RATIO = 0.8f; //计算特征点主方向时,直方图的峰值比
  21. const int DESCR_WIDTH = 4; //描述子直方图的网格大小(4x4)
  22. const int DESCR_HIST_BINS = 8; //每个网格中直方图角度方向的维度
  23. const float DESCR_MAG_THR = 0.2f; //描述子幅度阈值
  24. const float DESCR_SCL_FCTR = 3.0f; //计算描述子时,每个网格的大小因子
  25. const int SAR_SIFT_GLOH_ANG_GRID = 8; //GLOH网格沿角度方向等分区间个数
  26. const int SAR_SIFT_DES_ANG_BINS = 8; //像素梯度方向在0-360度内等分区间个数
  27. const float SAR_SIFT_RADIUS_DES = 12.0f; //描述子邻域半径
  28. const int Mmax = 8; //像素梯度方向在0-360度内等分区间个数
  29. const double T = 100.0; //sobel算子去除冗余特征点的阈值
  30. const float SAR_SIFT_GLOH_RATIO_R1_R2 = 0.73f;//GLOH网格中间圆半径和外圆半径之比
  31. const float SAR_SIFT_GLOH_RATIO_R1_R3 = 0.25f;//GLOH网格最内层圆半径和外圆半径之比
  32. #define Feature_Point_Minimum 1500 //输入图像特征点最小个数
  33. #define We 0.2
  34. #define Wn 0.5
  35. #define Row_num 3
  36. #define Col_num 3
  37. #define SIFT_FIXPT_SCALE 48 //不理解,后面可查原论文
  38. /************************sift类*******************************/
  39. class mySift
  40. {
  41. public:
  42. //默认构造函数
  43. mySift(int nfeatures = 0, int nOctaveLayers = 3, double contrastThreshold = 0.03,
  44. double edgeThreshold = 10, double sigma = 1.6, bool double_size = true) :nfeatures(nfeatures),
  45. nOctaveLayers(nOctaveLayers), contrastThreshold(contrastThreshold),
  46. edgeThreshold(edgeThreshold), sigma(sigma), double_size(double_size) {}
  47. //获得尺度空间每组中间层数
  48. int get_nOctave_layers() { return nOctaveLayers; }
  49. //获得图像尺度是否扩大一倍
  50. bool get_double_size() { return double_size; }
  51. //计算金字塔组数
  52. int num_octaves(const Mat& image);
  53. //生成高斯金字塔第一组,第一层图像
  54. void create_initial_image(const Mat& image, Mat& init_image);
  55. //使用 sobel 算子创建高斯金字塔第一层图像,以减少冗余特征点
  56. void sobel_create_initial_image(const Mat& image, Mat& init_image);
  57. //创建高斯金字塔
  58. void build_gaussian_pyramid(const Mat& init_image, vector<vector<Mat>>& gauss_pyramid, int nOctaves);
  59. //创建高斯差分金字塔
  60. void build_dog_pyramid(vector<vector<Mat>>& dog_pyramid, const vector<vector<Mat>>& gauss_pyramid);
  61. //该函数生成高斯差分金字塔
  62. void amplit_orient(const Mat& image, vector<Mat>& amplit, vector<Mat>& orient, float scale, int nums);
  63. //DOG金字塔特征点检测
  64. void find_scale_space_extrema(const vector<vector<Mat>>& dog_pyr, const vector<vector<Mat>>& gauss_pyr,
  65. vector<KeyPoint>& keypoints);
  66. //DOG金字塔特征点检测,特征点方向细化版
  67. void find_scale_space_extrema1(const vector<vector<Mat>>& dog_pyr, vector<vector<Mat>>& gauss_pyr,
  68. vector<KeyPoint>& keypoints);
  69. //计算特征点的描述子
  70. void calc_sift_descriptors(const vector<vector<Mat>>& gauss_pyr, vector<KeyPoint>& keypoints,
  71. Mat& descriptors, const vector<Mat>& amplit, const vector<Mat>& orient);
  72. //构建空间尺度—主要是为了获取 amplit 和 orient 在使用 GLOH 描述子的时候使用
  73. void build_sar_sift_space(const Mat& image, vector<Mat>& sar_harris_fun, vector<Mat>& amplit, vector<Mat>& orient);
  74. //GLOH 计算一个特征描述子
  75. void calc_gloh_descriptors(const vector<Mat>& amplit, const vector<Mat>& orient, const vector<KeyPoint>& keys, Mat& descriptors);
  76. //特征点检测
  77. void detect(const Mat& image, vector<vector<Mat>>& gauss_pyr, vector<vector<Mat>>& dog_pyr, vector<KeyPoint>& keypoints,
  78. vector<vector<vector<float>>>& all_cell_contrasts,
  79. vector<vector<float>>& average_contrast, vector<vector<int>>& n_cells, vector<int>& num_cell, vector<vector<int>>& available_n,
  80. vector<int>& available_num, vector<KeyPoint>& final_keypoints,
  81. vector<KeyPoint>& Final_keypoints, vector<KeyPoint>& Final_Keypoints);
  82. //特征点描述
  83. void comput_des(const vector<vector<Mat>>& gauss_pyr, vector<KeyPoint>& final_keypoints, const vector<Mat>& amplit,
  84. const vector<Mat>& orient, Mat& descriptors);
  85. private:
  86. int nfeatures; //设定检测的特征点的个数值,如果此值设置为0,则不影响结果
  87. int nOctaveLayers; //每组金字塔中间层数
  88. double contrastThreshold; //对比度阈值(D(x))
  89. double edgeThreshold; //特征点边缘曲率阈值
  90. double sigma; //高斯尺度空间初始层的尺度
  91. bool double_size; //是否上采样原始图像
  92. };//注意类结束的分号

2、mySift.cpp

  1. #include"mySift.h"
  2. #include<string>
  3. #include<cmath>
  4. #include<iostream> //输入输出
  5. #include<vector> //vector
  6. #include<algorithm>
  7. #include<numeric> //用于容器元素求和
  8. #include<opencv2\core\hal\hal.hpp>
  9. #include<opencv2\core\hal\intrin.hpp>
  10. #include<opencv2\opencv.hpp>
  11. #include<opencv2\core\core.hpp> //opencv基本数据结构
  12. #include<opencv2\highgui\highgui.hpp> //图像界面
  13. #include<opencv2\imgproc\imgproc.hpp> //基本图像处理函数
  14. #include<opencv2\features2d\features2d.hpp> //特征提取
  15. #include<opencv2\imgproc\types_c.h>
  16. #include<opencv2\videoio.hpp>
  17. #include <highgui\highgui.hpp>
  18. #include <imgproc\imgproc.hpp>
  19. /******************根据输入图像大小计算高斯金字塔的组数****************************/
  20. /*image表示原始输入灰度图像,inline函数必须在声明处定义
  21. double_size_image表示是否在构建金字塔之前上采样原始图像
  22. */
  23. int mySift::num_octaves(const Mat& image)
  24. {
  25. int temp;
  26. float size_temp = (float)min(image.rows, image.cols);
  27. temp = cvRound(log(size_temp) / log((float)2) - 2);
  28. if (double_size)
  29. temp += 1;
  30. if (temp > MAX_OCTAVES) //尺度空间最大组数设置为MAX_OCTAVES
  31. temp = MAX_OCTAVES;
  32. return temp;
  33. }
  34. /************************sobel滤波器计算高斯尺度空间图像梯度大小*****************************/
  35. void sobelfilter(Mat& image, Mat& G)
  36. {
  37. // image 是经过归一化后的数据 (0,1)
  38. int rows = image.rows;
  39. int cols = image.cols;
  40. float dx = 0.0, dy = 0.0;
  41. //cv::Mat Gx = cv::Mat::zeros(rows, cols, CV_32FC1); //包含了图像像素在水平方向上的导数的近似值的图像
  42. //cv::Mat Gy = cv::Mat::zeros(rows, cols, CV_32FC1); //包含了图像像素在垂直方向上的导数的近似值的图像
  43. G = Mat::zeros(rows, cols, CV_32FC1); //在每个像素点处的灰度大小由Gx和Gy共同决定
  44. double v = 0.0, vx, vy;
  45. //利用 sobel 算子求梯度幅度图像
  46. for (int i = 0; i < rows; i++)
  47. {
  48. for (int j = 0; j < cols; j++)
  49. {
  50. v = 0.0;
  51. if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)
  52. {
  53. G.at<float>(i, j) = 0.0;
  54. }
  55. else
  56. {
  57. float dx = image.at<float>(i - 1, j + 1) - image.at<float>(i - 1, j - 1)
  58. + 2 * image.at<float>(i, j + 1) - 2 * image.at<float>(i, j - 1)
  59. + image.at<float>(i + 1, j + 1) - image.at<float>(i + 1, j - 1);
  60. float dy = image.at<float>(i + 1, j - 1) - image.at<float>(i - 1, j - 1)
  61. + 2 * image.at<float>(i + 1, j) - 2 * image.at<float>(i - 1, j) +
  62. image.at<float>(i + 1, j + 1) - image.at<float>(i - 1, j + 1);
  63. v = abs(dx) + abs(dy); //简化后 G = |Gx| + |Gy|
  64. //保证像素值在有效范围内
  65. v = fmax(v, 0); //返回浮点数中较大的一个
  66. v = fmin(v, 255); //返回浮点数中较小的一个
  67. if (v > T) //T为阈值等于50
  68. G.at<float>(i, j) = (float)v;
  69. else
  70. G.at<float>(i, j) = 0.0;
  71. }
  72. }
  73. }
  74. //水平方向上的导数的近似值的图像
  75. /*for (int i = 0; i < rows; i++)
  76. {
  77. for (int j = 0; j < cols; j++)
  78. {
  79. vx = 0;
  80. if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)
  81. Gx.at<float>(i, j) = 0;
  82. else
  83. {
  84. dx = image.at<float>(i - 1, j + 1) - image.at<float>(i - 1, j - 1)
  85. + 2 * image.at<float>(i, j + 1) - 2 * image.at<float>(i, j - 1)
  86. + image.at<float>(i + 1, j + 1) - image.at<float>(i + 1, j - 1);
  87. vx = abs(dx);
  88. vx = fmax(vx, 0); vx = fmin(vx, 255);
  89. Gx.at<float>(i, j) = (float)vx;
  90. }
  91. }
  92. }*/
  93. //垂直方向上的导数的近似值的图像
  94. /*for (int i = 0; i < rows; i++)
  95. {
  96. for (int j = 0; j < cols; j++)
  97. {
  98. vy = 0;
  99. if (i == 0 || j == 0 || i == rows - 1 || j == cols - 1)
  100. Gy.at<float>(i, j) = 0;
  101. else
  102. {
  103. dy = image.at<float>(i + 1, j - 1) - image.at<float>(i - 1, j - 1)
  104. + 2 * image.at<float>(i + 1, j) - 2 * image.at<float>(i - 1, j) +
  105. image.at<float>(i + 1, j + 1) - image.at<float>(i - 1, j + 1);
  106. vy = abs(dy);
  107. vy = fmax(vy, 0); vx = fmin(vy, 255);
  108. Gy.at<float>(i, j) = (float)vy;
  109. }
  110. }
  111. }*/
  112. //cv::imshow("Gx", Gx); // horizontal
  113. //cv::imshow("Gy", Gy); // vertical
  114. //cv::imshow("G", G); // gradient
  115. }
  116. /*********该函数根据尺度和窗口半径生成ROEWA滤波模板************/
  117. /*size表示核半径,因此核宽度是2*size+1
  118. scale表示指数权重参数
  119. kernel表示生成的滤波核
  120. */
  121. static void roewa_kernel(int size, float scale, Mat& kernel)
  122. {
  123. kernel.create(2 * size + 1, 2 * size + 1, CV_32FC1);
  124. for (int i = -size; i <= size; ++i)
  125. {
  126. float* ptr_k = kernel.ptr<float>(i + size);
  127. for (int j = -size; j <= size; ++j)
  128. {
  129. ptr_k[j + size] = exp(-1.f * (abs(i) + abs(j)) / scale);
  130. }
  131. }
  132. }
  133. /************************创建高斯金字塔第一组,第一层图像************************************/
  134. /*image表示输入原始图像
  135. init_image表示生成的高斯尺度空间的第一层图像
  136. */
  137. void mySift::create_initial_image(const Mat& image, Mat& init_image)
  138. {
  139. Mat gray_image;
  140. if (image.channels() != 1)
  141. cvtColor(image, gray_image, CV_RGB2GRAY); //转换为灰度图像
  142. else
  143. gray_image = image.clone();
  144. Mat floatImage; //转换到0-1之间的浮点类型数据归一化,方便接下来的处理
  145. //float_image=(float)gray_image*(1.0/255.0)
  146. gray_image.convertTo(floatImage, CV_32FC1, 1.0 / 255.0, 0);
  147. double sig_diff = 0;
  148. if (double_size)
  149. {
  150. Mat temp_image;
  151. //通过插值的方法改变图像尺寸的大小
  152. resize(floatImage, temp_image, Size(2 * floatImage.cols, 2 * floatImage.rows), 0.0, 0.0, INTER_LINEAR);
  153. //高斯平滑的标准差,值较大时平滑效果比较明显
  154. sig_diff = sqrt(sigma * sigma - 4.0 * INIT_SIGMA * INIT_SIGMA);
  155. //高斯滤波窗口大小选择很重要,这里选择(4*sig_diff_1+1)-(6*sig_diff+1)之间,且四舍五入
  156. int kernel_width = 2 * cvRound(GAUSS_KERNEL_RATIO * sig_diff) + 1;
  157. Size kernel_size(kernel_width, kernel_width);
  158. //对图像进行平滑处理(高斯模糊),即降低图像的分辨率,高斯模糊是实现尺度变换的唯一变换核,并其实唯一的线性核
  159. GaussianBlur(temp_image, init_image, kernel_size, sig_diff, sig_diff);
  160. }
  161. else
  162. {
  163. sig_diff = sqrt(sigma * sigma - 1.0 * INIT_SIGMA * INIT_SIGMA);
  164. //高斯滤波窗口大小选择很重要,这里选择(4*sig_diff_1+1)-(6*sig_diff+1)之间
  165. int kernel_width = 2 * cvRound(GAUSS_KERNEL_RATIO * sig_diff) + 1;
  166. Size kernel_size(kernel_width, kernel_width);
  167. GaussianBlur(floatImage, init_image, kernel_size, sig_diff, sig_diff);
  168. }
  169. }
  170. /************************使用 sobel 算子创建高斯金字塔第一组,第一层图像****************************/
  171. //目的是为了减少冗余特征点
  172. void mySift::sobel_create_initial_image(const Mat& image, Mat& init_image)
  173. {
  174. Mat gray_image, gray_images; //gray_images用于存放经过sobel算子操作后的图像
  175. if (image.channels() != 1)
  176. cvtColor(image, gray_image, CV_RGB2GRAY); //转换为灰度图像
  177. else
  178. gray_image = image.clone();
  179. sobelfilter(gray_image, gray_images);
  180. Mat floatImage; //转换到0-1之间的浮点类型数据归一化,方便接下来的处理
  181. //float_image=(float)gray_image*(1.0/255.0)
  182. gray_images.convertTo(floatImage, CV_32FC1, 1.0 / 255.0, 0);
  183. double sig_diff = 0;
  184. if (double_size)
  185. {
  186. Mat temp_image;
  187. //通过插值的方法改变图像尺寸的大小
  188. resize(floatImage, temp_image, Size(2 * floatImage.cols, 2 * floatImage.rows), 0.0, 0.0, INTER_LINEAR);
  189. //高斯平滑的标准差,值较大时平滑效果比较明显
  190. sig_diff = sqrt(sigma * sigma - 4.0 * INIT_SIGMA * INIT_SIGMA);
  191. //高斯滤波窗口大小选择很重要,这里选择(4*sig_diff_1+1)-(6*sig_diff+1)之间,且四舍五入
  192. int kernel_width = 2 * cvRound(GAUSS_KERNEL_RATIO * sig_diff) + 1;
  193. Size kernel_size(kernel_width, kernel_width);
  194. //对图像进行平滑处理(高斯模糊),即降低图像的分辨率,高斯模糊是实现尺度变换的唯一变换核,并其实唯一的线性核
  195. GaussianBlur(temp_image, init_image, kernel_size, sig_diff, sig_diff);
  196. }
  197. else
  198. {
  199. sig_diff = sqrt(sigma * sigma - 1.0 * INIT_SIGMA * INIT_SIGMA);
  200. //高斯滤波窗口大小选择很重要,这里选择(4*sig_diff_1+1)-(6*sig_diff+1)之间
  201. int kernel_width = 2 * cvRound(GAUSS_KERNEL_RATIO * sig_diff) + 1;
  202. Size kernel_size(kernel_width, kernel_width);
  203. GaussianBlur(floatImage, init_image, kernel_size, sig_diff, sig_diff);
  204. }
  205. }
  206. /**************************生成高斯金字塔*****************************************/
  207. /*init_image表示已经生成的高斯金字塔第一层图像
  208. gauss_pyramid表示生成的高斯金字塔
  209. nOctaves表示高斯金字塔的组数
  210. */
  211. void mySift::build_gaussian_pyramid(const Mat& init_image, vector<vector<Mat>>& gauss_pyramid, int nOctaves)
  212. {
  213. vector<double> sig;
  214. sig.push_back(sigma);
  215. double k = pow(2.0, 1.0 / nOctaveLayers); //高斯金字塔每一层的系数 k
  216. for (int i = 1; i < nOctaveLayers + 3; ++i)
  217. {
  218. double prev_sig = pow(k, i - 1) * sigma; //每一个尺度层的尺度
  219. double curr_sig = k * prev_sig;
  220. //组内每层的尺度坐标计算公式
  221. sig.push_back(sqrt(curr_sig * curr_sig - prev_sig * prev_sig));
  222. }
  223. gauss_pyramid.resize(nOctaves);
  224. for (int i = 0; i < nOctaves; ++i)
  225. {
  226. gauss_pyramid[i].resize(nOctaveLayers + 3);
  227. }
  228. for (int i = 0; i < nOctaves; ++i) //对于每一组
  229. {
  230. for (int j = 0; j < nOctaveLayers + 3; ++j) //对于组内的每一层
  231. {
  232. if (i == 0 && j == 0) //第一组,第一层
  233. gauss_pyramid[0][0] = init_image;
  234. else if (j == 0)
  235. {
  236. resize(gauss_pyramid[i - 1][3], gauss_pyramid[i][0],
  237. Size(gauss_pyramid[i - 1][3].cols / 2,
  238. gauss_pyramid[i - 1][3].rows / 2), 0, 0, INTER_LINEAR);
  239. }
  240. else
  241. {
  242. //高斯滤波窗口大小选择很重要,这里选择(4*sig_diff_1+1)-(6*sig_diff+1)之间
  243. int kernel_width = 2 * cvRound(GAUSS_KERNEL_RATIO * sig[j]) + 1;
  244. Size kernel_size(kernel_width, kernel_width);
  245. GaussianBlur(gauss_pyramid[i][j - 1], gauss_pyramid[i][j], kernel_size, sig[j], sig[j]);
  246. }
  247. }
  248. }
  249. }
  250. /*******************生成高斯差分金字塔,即LOG金字塔*************************/
  251. /*dog_pyramid表示DOG金字塔
  252. gauss_pyramin表示高斯金字塔*/
  253. void mySift::build_dog_pyramid(vector<vector<Mat>>& dog_pyramid, const vector<vector<Mat>>& gauss_pyramid)
  254. {
  255. vector<vector<Mat>>::size_type nOctaves = gauss_pyramid.size();
  256. for (vector<vector<Mat>>::size_type i = 0; i < nOctaves; ++i)
  257. {
  258. //用于存放每一个梯度中的所有尺度层
  259. vector<Mat> temp_vec;
  260. for (auto j = 0; j < nOctaveLayers + 2; ++j)
  261. {
  262. Mat temp_img = gauss_pyramid[i][j + 1] - gauss_pyramid[i][j];
  263. temp_vec.push_back(temp_img);
  264. }
  265. dog_pyramid.push_back(temp_vec);
  266. temp_vec.clear();
  267. }
  268. }
  269. /***********生成高斯差分金字塔当前层对应的梯度幅度图像和梯度方向图像***********/
  270. /*image为高斯差分金字塔当前层图像
  271. *amplit为当前层梯度幅度图像
  272. *orient为当前层梯度方向图像
  273. *scale当前层尺度
  274. *nums为相对底层的层数
  275. */
  276. void mySift::amplit_orient(const Mat& image, vector<Mat>& amplit, vector<Mat>& orient, float scale, int nums)
  277. {
  278. //分配内存
  279. amplit.resize(Mmax * nOctaveLayers);
  280. orient.resize(Mmax * nOctaveLayers);
  281. int radius = cvRound(2 * scale);
  282. Mat kernel; //kernel(2 * radius + 1, 2 * radius + 1, CV_32FC1);
  283. roewa_kernel(radius, scale, kernel); //返回滤波核,也即指数部分,存放在矩阵的右下角
  284. //四个滤波模板生成
  285. Mat W34 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1); //把kernel矩阵下半部分复制到对应部分
  286. Mat W12 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1); //把kernel矩阵上半部分复制到对应部分
  287. Mat W14 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1); //把kernel矩阵右半部分复制到对应部分
  288. Mat W23 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1); //把kernel矩阵左半部分复制到对应部分
  289. kernel(Range(radius + 1, 2 * radius + 1), Range::all()).copyTo(W34(Range(radius + 1, 2 * radius + 1), Range::all()));
  290. kernel(Range(0, radius), Range::all()).copyTo(W12(Range(0, radius), Range::all()));
  291. kernel(Range::all(), Range(radius + 1, 2 * radius + 1)).copyTo(W14(Range::all(), Range(radius + 1, 2 * radius + 1)));
  292. kernel(Range::all(), Range(0, radius)).copyTo(W23(Range::all(), Range(0, radius)));
  293. //滤波
  294. Mat M34, M12, M14, M23;
  295. double eps = 0.00001;
  296. //float_image为图像归一化后的图像数据,做卷积运算
  297. filter2D(image, M34, CV_32FC1, W34, Point(-1, -1), eps);
  298. filter2D(image, M12, CV_32FC1, W12, Point(-1, -1), eps);
  299. filter2D(image, M14, CV_32FC1, W14, Point(-1, -1), eps);
  300. filter2D(image, M23, CV_32FC1, W23, Point(-1, -1), eps);
  301. //计算水平梯度和竖直梯度
  302. Mat Gx, Gy;
  303. log((M14) / (M23), Gx);
  304. log((M34) / (M12), Gy);
  305. //计算梯度幅度和梯度方向
  306. magnitude(Gx, Gy, amplit[nums]); //梯度幅度图像,平方和开平方
  307. phase(Gx, Gy, orient[nums], true); //梯度方向图像
  308. }
  309. /***********************该函数计算尺度空间特征点的主方向,用于后面特征点的检测***************************/
  310. /*image表示特征点所在位置的高斯图像,后面可对着源码进行修改
  311. pt表示特征点的位置坐标(x,y)
  312. scale特征点的尺度
  313. n表示直方图bin个数
  314. hist表示计算得到的直方图
  315. 函数返回值是直方图hist中的最大数值*/
  316. static float clac_orientation_hist(const Mat& image, Point pt, float scale, int n, float* hist)
  317. {
  318. int radius = cvRound(ORI_RADIUS * scale); //特征点邻域半径(3*1.5*scale)
  319. int len = (2 * radius + 1) * (2 * radius + 1); //特征点邻域像素总个数(最大值)
  320. float sigma = ORI_SIG_FCTR * scale; //特征点邻域高斯权重标准差(1.5*scale)
  321. float exp_scale = -1.f / (2 * sigma * sigma); //权重的指数部分
  322. //使用AutoBuffer分配一段内存,这里多出4个空间的目的是为了方便后面平滑直方图的需要
  323. AutoBuffer<float> buffer((4 * len) + n + 4);
  324. //X保存水平差分,Y保存数值差分,Mag保存梯度幅度,Ori保存梯度角度,W保存高斯权重
  325. float* X = buffer, * Y = buffer + len, * Mag = Y, * Ori = Y + len, * W = Ori + len;
  326. float* temp_hist = W + len + 2; //临时保存直方图数据
  327. for (int i = 0; i < n; ++i)
  328. temp_hist[i] = 0.f; //数据清零
  329. //计算邻域像素的水平差分和竖直差分
  330. int k = 0;
  331. for (int i = -radius; i < radius; ++i)
  332. {
  333. int y = pt.y + i; //邻域点的纵坐标
  334. if (y <= 0 || y >= image.rows - 1)
  335. continue;
  336. for (int j = -radius; j < radius; ++j)
  337. {
  338. int x = pt.x + j;
  339. if (x <= 0 || x >= image.cols - 1)
  340. continue;
  341. float dx = image.at<float>(y, x + 1) - image.at<float>(y, x - 1); //水平差分
  342. float dy = image.at<float>(y + 1, x) - image.at<float>(y - 1, x); //竖直差分
  343. //保存水平差分和竖直差分及其对应的权重
  344. X[k] = dx;
  345. Y[k] = dy;
  346. W[k] = (i * i + j * j) * exp_scale;
  347. ++k;
  348. }
  349. }
  350. len = k; //邻域内特征点的个数
  351. cv::hal::exp(W, W, len); //计算邻域内所有像素的高斯权重
  352. cv::hal::fastAtan2(Y, X, Ori, len, true); //计算邻域内所有像素的梯度方向,角度范围0-360度
  353. cv::hal::magnitude32f(X, Y, Mag, len); //计算邻域内所有像素的梯度幅度,计算的是数学意义上的梯度
  354. //遍历邻域的像素
  355. for (int i = 0; i < len; ++i)
  356. {
  357. int bin = cvRound((n / 360.f) * Ori[i]); //利用像素的梯度方向,约束bin的范围在[0,(n-1)]
  358. //像素点梯度方向为360度时,和0°一样
  359. if (bin >= n)
  360. bin = bin - n;
  361. if (bin < 0)
  362. bin = bin + n;
  363. temp_hist[bin] = temp_hist[bin] + Mag[i] * W[i]; //统计邻域内像素各个方向在梯度直方图的幅值(加权后的幅值)
  364. }
  365. //平滑直方图
  366. temp_hist[-1] = temp_hist[n - 1];
  367. temp_hist[-2] = temp_hist[n - 2];
  368. temp_hist[n] = temp_hist[0];
  369. temp_hist[n + 1] = temp_hist[1];
  370. for (int i = 0; i < n; ++i)
  371. {
  372. hist[i] = (temp_hist[i - 2] + temp_hist[i + 2]) * (1.f / 16.f) +
  373. (temp_hist[i - 1] + temp_hist[i + 1]) * (4.f / 16.f) +
  374. temp_hist[i] * (6.f / 16.f);
  375. }
  376. //获得直方图中最大值
  377. float max_value = hist[0];
  378. for (int i = 1; i < n; ++i)
  379. {
  380. if (hist[i] > max_value)
  381. max_value = hist[i];
  382. }
  383. return max_value;
  384. }
  385. /***********************使用 sobel 滤波器定义的新梯度计算尺度空间特征点的主方向**************************/
  386. static float clac_orientation_hist_2(Mat& image, Point pt, float scale, int n, float* hist)
  387. {
  388. Mat output_image; //使用 sobel 滤波器计算的图像的梯度幅度图像
  389. sobelfilter(image, output_image); //使用 sobel 滤波器求高斯差分图像的梯度幅度图像
  390. int radius = cvRound(ORI_RADIUS * scale); //特征点邻域半径(3*1.5*scale)
  391. int len = (2 * radius + 1) * (2 * radius + 1); //特征点邻域像素总个数(最大值)
  392. float sigma = ORI_SIG_FCTR * scale; //特征点邻域高斯权重标准差(1.5*scale)
  393. float exp_scale = -1.f / (2 * sigma * sigma); //权重的指数部分
  394. //使用AutoBuffer分配一段内存,这里多出4个空间的目的是为了方便后面平滑直方图的需要
  395. AutoBuffer<float> buffer((4 * len) + n + 4);
  396. //X保存水平差分,Y保存数值差分,Mag保存梯度幅度,Ori保存梯度角度,W保存高斯权重
  397. float* X = buffer, * Y = buffer + len, * Mag = Y, * Ori = Y + len, * W = Ori + len;
  398. float* temp_hist = W + len + 2; //临时保存直方图数据
  399. for (int i = 0; i < n; ++i)
  400. temp_hist[i] = 0.f; //数据清零
  401. //计算邻域像素的水平差分和竖直差分
  402. int k = 0;
  403. for (int i = -radius; i < radius; ++i)
  404. {
  405. int y = pt.y + i; //邻域点的纵坐标,行
  406. if (y <= 0 || y >= output_image.rows - 1)
  407. continue;
  408. for (int j = -radius; j < radius; ++j)
  409. {
  410. int x = pt.x + j; //邻域点的纵坐标,列
  411. if (x <= 0 || x >= output_image.cols - 1)
  412. continue;
  413. //float dx = image.at<float>(y, x + 1) - image.at<float>(y, x - 1); //水平差分
  414. float dx = output_image.at<float>(y - 1, x + 1) - output_image.at<float>(y - 1, x - 1)
  415. + 2 * output_image.at<float>(y, x + 1) - 2 * output_image.at<float>(y, x - 1)
  416. + output_image.at<float>(y + 1, x + 1) - output_image.at<float>(y + 1, x - 1);
  417. float dy = output_image.at<float>(y + 1, x - 1) - output_image.at<float>(y - 1, x - 1)
  418. + 2 * output_image.at<float>(y + 1, x) - 2 * output_image.at<float>(y - 1, x) +
  419. output_image.at<float>(y + 1, x + 1) - output_image.at<float>(y - 1, x + 1);
  420. /*float dx = image.at<float>(y - 1, x + 1) - image.at<float>(y - 1, x - 1)
  421. + 2 * image.at<float>(y, x + 1) - 2 * image.at<float>(y, x - 1)
  422. + image.at<float>(y + 1, x + 1) - image.at<float>(y + 1, x - 1);
  423. float dy = image.at<float>(y + 1, x - 1) - image.at<float>(y - 1, x - 1)
  424. + 2 * image.at<float>(y + 1, x) - 2 * image.at<float>(y - 1, x) +
  425. image.at<float>(y + 1, x + 1) - image.at<float>(y - 1, x + 1);*/
  426. //保存水平差分和竖直差分及其对应的权重
  427. X[k] = dx;
  428. Y[k] = dy;
  429. W[k] = (i * i + j * j) * exp_scale;
  430. ++k;
  431. }
  432. }
  433. len = k; //邻域内特征点的个数
  434. cv::hal::exp(W, W, len); //计算邻域内所有像素的高斯权重
  435. cv::hal::fastAtan2(Y, X, Ori, len, true); //计算邻域内所有像素的梯度方向,角度范围0-360度
  436. cv::hal::magnitude32f(X, Y, Mag, len); //计算邻域内所有像素的梯度幅度,计算的是数学意义上的梯度
  437. //遍历邻域的像素
  438. for (int i = 0; i < len; ++i)
  439. {
  440. int bin = cvRound((n / 360.f) * Ori[i]); //利用像素的梯度方向,约束bin的范围在[0,(n-1)]
  441. //像素点梯度方向为360度时,和0°一样
  442. if (bin >= n)
  443. bin = bin - n;
  444. if (bin < 0)
  445. bin = bin + n;
  446. temp_hist[bin] = temp_hist[bin] + Mag[i] * W[i]; //统计邻域内像素各个方向在梯度直方图的幅值(加权后的幅值)
  447. }
  448. //平滑直方图
  449. temp_hist[-1] = temp_hist[n - 1];
  450. temp_hist[-2] = temp_hist[n - 2];
  451. temp_hist[n] = temp_hist[0];
  452. temp_hist[n + 1] = temp_hist[1];
  453. for (int i = 0; i < n; ++i)
  454. {
  455. hist[i] = (temp_hist[i - 2] + temp_hist[i + 2]) * (1.f / 16.f) +
  456. (temp_hist[i - 1] + temp_hist[i + 1]) * (4.f / 16.f) +
  457. temp_hist[i] * (6.f / 16.f);
  458. }
  459. //获得直方图中最大值
  460. float max_value = hist[0];
  461. for (int i = 1; i < n; ++i)
  462. {
  463. if (hist[i] > max_value)
  464. max_value = hist[i];
  465. }
  466. return max_value;
  467. }
  468. /******************该函数计算特征点主方向,用于LOGH版本*********************/
  469. /*amplit表示特征点所在层的梯度幅度,即输入图像对应像素点的梯度存在了对应位置
  470. orient表示特征点所在层的梯度方向,0-360度
  471. point表示特征点坐标
  472. scale表示特征点的所在层的尺度
  473. hist表示生成的直方图
  474. n表示主方向直方图bin个数
  475. */
  476. static float calc_orient_hist(const Mat& amplit, const Mat& orient, Point pt, float scale, float* hist, int n)
  477. {
  478. //暂且认为是只进行了下采样,没有进行高斯模糊
  479. int num_row = amplit.rows;
  480. int num_col = amplit.cols;
  481. Point point(cvRound(pt.x), cvRound(pt.y));
  482. //int radius = cvRound(SAR_SIFT_FACT_RADIUS_ORI * scale);
  483. int radius = cvRound(6 * scale);
  484. radius = min(radius, min(num_row / 2, num_col / 2));
  485. float gauss_sig = 2 * scale; //高斯加权标准差
  486. float exp_temp = -1.f / (2 * gauss_sig * gauss_sig); //权重指数部分
  487. //邻域区域
  488. int radius_x_left = point.x - radius;
  489. int radius_x_right = point.x + radius;
  490. int radius_y_up = point.y - radius;
  491. int radius_y_down = point.y + radius;
  492. //防止越界
  493. if (radius_x_left < 0)
  494. radius_x_left = 0;
  495. if (radius_x_right > num_col - 1)
  496. radius_x_right = num_col - 1;
  497. if (radius_y_up < 0)
  498. radius_y_up = 0;
  499. if (radius_y_down > num_row - 1)
  500. radius_y_down = num_row - 1;
  501. //此时特征点周围矩形区域相对于本矩形区域的中心
  502. int center_x = point.x - radius_x_left;
  503. int center_y = point.y - radius_y_up;
  504. //矩形区域的边界,计算高斯权值
  505. Range x_rng(-(point.x - radius_x_left), radius_x_right - point.x);
  506. Range y_rng(-(point.y - radius_y_up), radius_y_down - point.y);
  507. Mat gauss_weight;
  508. gauss_weight.create(y_rng.end - y_rng.start + 1, x_rng.end - x_rng.start + 1, CV_32FC1);
  509. //求各个像素点的高斯权重
  510. for (int i = y_rng.start; i <= y_rng.end; ++i)
  511. {
  512. float* ptr_gauss = gauss_weight.ptr<float>(i - y_rng.start);
  513. for (int j = x_rng.start; j <= x_rng.end; ++j)
  514. ptr_gauss[j - x_rng.start] = exp((i * i + j * j) * exp_temp);
  515. }
  516. //索引特征点周围的像素梯度幅度,梯度方向
  517. Mat sub_amplit = amplit(Range(radius_y_up, radius_y_down + 1), Range(radius_x_left, radius_x_right + 1));
  518. Mat sub_orient = orient(Range(radius_y_up, radius_y_down + 1), Range(radius_x_left, radius_x_right + 1));
  519. //Mat W = sub_amplit.mul(gauss_weight); //加入高斯权重,计算高斯权重时,正确匹配点对反而变少了
  520. Mat W = sub_amplit; //没加高斯权重,梯度幅值
  521. //计算直方图
  522. AutoBuffer<float> buffer(n + 4);
  523. float* temp_hist = buffer + 2;
  524. for (int i = 0; i < n; ++i)
  525. temp_hist[i] = 0.f;
  526. for (int i = 0; i < sub_orient.rows; i++)
  527. {
  528. float* ptr_1 = W.ptr<float>(i);
  529. float* ptr_2 = sub_orient.ptr<float>(i);
  530. for (int j = 0; j < sub_orient.cols; j++)
  531. {
  532. if (((i - center_y) * (i - center_y) + (j - center_x) * (j - center_x)) < radius * radius)
  533. {
  534. int bin = cvRound(ptr_2[j] * n / 360.f);
  535. if (bin > n)
  536. bin = bin - n;
  537. if (bin < 0)
  538. bin = bin + n;
  539. temp_hist[bin] += ptr_1[j];
  540. }
  541. }
  542. }
  543. //平滑直方图,可以防止突变
  544. temp_hist[-1] = temp_hist[n - 1];
  545. temp_hist[-2] = temp_hist[n - 2];
  546. temp_hist[n] = temp_hist[0];
  547. temp_hist[n + 1] = temp_hist[1];
  548. for (int i = 0; i < n; ++i)
  549. {
  550. hist[i] = (temp_hist[i - 2] + temp_hist[i + 2]) * (1.f / 16.f) +
  551. (temp_hist[i - 1] + temp_hist[i + 1]) * (4.f / 16.f) +
  552. temp_hist[i] * (6.f / 16.f);
  553. }
  554. //获得直方图中最大值
  555. float max_value = hist[0];
  556. for (int i = 1; i < n; ++i)
  557. {
  558. if (hist[i] > max_value)
  559. max_value = hist[i];
  560. }
  561. return max_value;
  562. }
  563. /****************************该函数精确定位特征点位置(x,y,scale),用于后面特征点的检测*************************/
  564. /*功能:确定特征点的位置,并通过主曲率消除边缘相应点,该版本是简化版
  565. dog_pry表示DOG金字塔
  566. kpt表示精确定位后该特征点的信息
  567. octave表示初始特征点所在的组
  568. layer表示初始特征点所在的层
  569. row表示初始特征点在图像中的行坐标
  570. col表示初始特征点在图像中的列坐标
  571. nOctaveLayers表示DOG金字塔每组中间层数,默认是3
  572. contrastThreshold表示对比度阈值,默认是0.04
  573. edgeThreshold表示边缘阈值,默认是10
  574. sigma表示高斯尺度空间最底层图像尺度,默认是1.6*/
  575. static bool adjust_local_extrema_1(const vector<vector<Mat>>& dog_pyr, KeyPoint& kpt, int octave, int& layer, int& row,
  576. int& col, int nOctaveLayers, float contrastThreshold, float edgeThreshold, float sigma)
  577. {
  578. float xi = 0, xr = 0, xc = 0;
  579. int i = 0;
  580. for (; i < MAX_INTERP_STEPS; ++i) //最大迭代次数
  581. {
  582. const Mat& img = dog_pyr[octave][layer]; //当前层图像索引
  583. const Mat& prev = dog_pyr[octave][layer - 1]; //之前层图像索引
  584. const Mat& next = dog_pyr[octave][layer + 1]; //下一层图像索引
  585. //特征点位置x方向,y方向,尺度方向的一阶偏导数
  586. float dx = (img.at<float>(row, col + 1) - img.at<float>(row, col - 1)) * (1.f / 2.f);
  587. float dy = (img.at<float>(row + 1, col) - img.at<float>(row - 1, col)) * (1.f / 2.f);
  588. float dz = (next.at<float>(row, col) - prev.at<float>(row, col)) * (1.f / 2.f);
  589. //计算特征点位置二阶偏导数
  590. float v2 = img.at<float>(row, col);
  591. float dxx = img.at<float>(row, col + 1) + img.at<float>(row, col - 1) - 2 * v2;
  592. float dyy = img.at<float>(row + 1, col) + img.at<float>(row - 1, col) - 2 * v2;
  593. float dzz = prev.at<float>(row, col) + next.at<float>(row, col) - 2 * v2;
  594. //计算特征点周围混合二阶偏导数
  595. float dxy = (img.at<float>(row + 1, col + 1) + img.at<float>(row - 1, col - 1) -
  596. img.at<float>(row + 1, col - 1) - img.at<float>(row - 1, col + 1)) * (1.f / 4.f);
  597. float dxz = (next.at<float>(row, col + 1) + prev.at<float>(row, col - 1) -
  598. next.at<float>(row, col - 1) - prev.at<float>(row, col + 1)) * (1.f / 4.f);
  599. float dyz = (next.at<float>(row + 1, col) + prev.at<float>(row - 1, col) -
  600. next.at<float>(row - 1, col) - prev.at<float>(row + 1, col)) * (1.f / 4.f);
  601. Matx33f H(dxx, dxy, dxz, dxy, dyy, dyz, dxz, dyz, dzz);
  602. Vec3f dD(dx, dy, dz);
  603. Vec3f X = H.solve(dD, DECOMP_SVD);
  604. xc = -X[0]; //x方向偏移量
  605. xr = -X[1]; //y方向偏移量
  606. xi = -X[2]; //尺度方向偏移量
  607. //如果三个方向偏移量都小于0.5,说明已经找到特征点准确位置
  608. if (abs(xc) < 0.5f && abs(xr) < 0.5f && abs(xi) < 0.5f)
  609. break;
  610. //如果其中一个方向的偏移量过大,则删除该点
  611. if (abs(xc) > (float)(INT_MAX / 3) ||
  612. abs(xr) > (float)(INT_MAX / 3) ||
  613. abs(xi) > (float)(INT_MAX / 3))
  614. return false;
  615. col = col + cvRound(xc);
  616. row = row + cvRound(xr);
  617. layer = layer + cvRound(xi);
  618. //如果特征点定位在边界区域,同样也需要删除
  619. if (layer<1 || layer>nOctaveLayers ||
  620. col<IMG_BORDER || col>img.cols - IMG_BORDER ||
  621. row<IMG_BORDER || row>img.rows - IMG_BORDER)
  622. return false;
  623. }
  624. //如果i=MAX_INTERP_STEPS,说明循环结束也没有满足条件,即该特征点需要被删除
  625. if (i >= MAX_INTERP_STEPS)
  626. return false;
  627. /**************************再次删除低响应点(对比度较低的点)********************************/
  628. //再次计算特征点位置x方向,y方向,尺度方向的一阶偏导数
  629. //高对比度的特征对图像的变形是稳定的
  630. {
  631. const Mat& img = dog_pyr[octave][layer];
  632. const Mat& prev = dog_pyr[octave][layer - 1];
  633. const Mat& next = dog_pyr[octave][layer + 1];
  634. float dx = (img.at<float>(row, col + 1) - img.at<float>(row, col - 1)) * (1.f / 2.f);
  635. float dy = (img.at<float>(row + 1, col) - img.at<float>(row - 1, col)) * (1.f / 2.f);
  636. float dz = (next.at<float>(row, col) - prev.at<float>(row, col)) * (1.f / 2.f);
  637. Matx31f dD(dx, dy, dz);
  638. float t = dD.dot(Matx31f(xc, xr, xi));
  639. float contr = img.at<float>(row, col) + t * 0.5f; //特征点响应 |D(x~)| 即对比度
  640. //Low建议contr阈值是0.03,但是RobHess等建议阈值为0.04/nOctaveLayers
  641. if (abs(contr) < contrastThreshold / nOctaveLayers) //阈值设为0.03时特征点数量过多
  642. return false;
  643. /******************************删除边缘响应比较强的点************************************/
  644. //再次计算特征点位置二阶偏导数,获取特征点出的 Hessian 矩阵,主曲率通过 2X2 的 Hessian 矩阵求出
  645. //一个定义不好的高斯差分算子的极值在横跨边缘的地方有较大的主曲率而在垂直边缘的方向有较小的主曲率
  646. float v2 = img.at<float>(row, col);
  647. float dxx = img.at<float>(row, col + 1) + img.at<float>(row, col - 1) - 2 * v2;
  648. float dyy = img.at<float>(row + 1, col) + img.at<float>(row - 1, col) - 2 * v2;
  649. float dxy = (img.at<float>(row + 1, col + 1) + img.at<float>(row - 1, col - 1) -
  650. img.at<float>(row + 1, col - 1) - img.at<float>(row - 1, col + 1)) * (1.f / 4.f);
  651. float det = dxx * dyy - dxy * dxy;
  652. float trace = dxx + dyy;
  653. //主曲率和阈值的对比判定
  654. if (det < 0 || (trace * trace * edgeThreshold >= det * (edgeThreshold + 1) * (edgeThreshold + 1)))
  655. return false;
  656. /*********到目前为止该特征的满足上面所有要求,保存该特征点信息***********/
  657. kpt.pt.x = ((float)col + xc) * (1 << octave); //相对于最底层的图像的x坐标
  658. kpt.pt.y = ((float)row + xr) * (1 << octave); //相对于最底层图像的y坐标
  659. kpt.octave = octave + (layer << 8); //组号保存在低字节,层号保存在高字节
  660. //相对于最底层图像的尺度
  661. kpt.size = sigma * powf(2.f, (layer + xi) / nOctaveLayers) * (1 << octave);
  662. kpt.response = abs(contr); //特征点响应值(对比度)
  663. return true;
  664. }
  665. }
  666. /****************************该函数精确定位特征点位置(x,y,scale),用于后面特征点的检测*************************/
  667. //该版本是 SIFT 原版,检测得到的特征点数量更多
  668. static bool adjust_local_extrema_2(const vector<vector<Mat>>& dog_pyr, KeyPoint& kpt, int octave, int& layer, int& row,
  669. int& col, int nOctaveLayers, float contrastThreshold, float edgeThreshold, float sigma)
  670. {
  671. const float img_scale = 1.f / (255 * SIFT_FIXPT_SCALE); //SIFT_FIXPT_SCALE=48
  672. const float deriv_scale = img_scale * 0.5f;
  673. const float second_deriv_scale = img_scale;
  674. const float cross_deriv_scale = img_scale * 0.25f;
  675. float xi = 0, xr = 0, xc = 0;
  676. int i = 0;
  677. for (; i < MAX_INTERP_STEPS; ++i) //最大迭代次数
  678. {
  679. const Mat& img = dog_pyr[octave][layer]; //当前层图像索引
  680. const Mat& prev = dog_pyr[octave][layer - 1]; //之前层图像索引
  681. const Mat& next = dog_pyr[octave][layer + 1]; //下一层图像索引
  682. //计算一阶偏导数,通过临近点差分求得
  683. float dx = (img.at<float>(row, col + 1) - img.at<float>(row, col - 1)) * deriv_scale;
  684. float dy = (img.at<float>(row + 1, col) - img.at<float>(row - 1, col)) * deriv_scale;
  685. float dz = (next.at<float>(row, col) - prev.at<float>(row, col)) * deriv_scale;
  686. //计算特征点位置二阶偏导数
  687. //float v2 = img.at<float>(row, col);
  688. float v2 = (float)img.at<float>(row, col) * 2.f;
  689. float dxx = (img.at<float>(row, col + 1) + img.at<float>(row, col - 1) - v2) * second_deriv_scale;
  690. float dyy = (img.at<float>(row + 1, col) + img.at<float>(row - 1, col) - v2) * second_deriv_scale;
  691. float dzz = (prev.at<float>(row, col) + next.at<float>(row, col) - v2) * second_deriv_scale;
  692. //计算特征点周围混合二阶偏导数
  693. float dxy = (img.at<float>(row + 1, col + 1) + img.at<float>(row - 1, col - 1) -
  694. img.at<float>(row + 1, col - 1) - img.at<float>(row - 1, col + 1)) * cross_deriv_scale;
  695. float dxz = (next.at<float>(row, col + 1) + prev.at<float>(row, col - 1) -
  696. next.at<float>(row, col - 1) - prev.at<float>(row, col + 1)) * cross_deriv_scale;
  697. float dyz = (next.at<float>(row + 1, col) + prev.at<float>(row - 1, col) -
  698. next.at<float>(row - 1, col) - prev.at<float>(row + 1, col)) * cross_deriv_scale;
  699. Matx33f H(dxx, dxy, dxz, dxy, dyy, dyz, dxz, dyz, dzz);
  700. Vec3f dD(dx, dy, dz);
  701. Vec3f X = H.solve(dD, DECOMP_SVD);
  702. xc = -X[0]; //x方向偏移量
  703. xr = -X[1]; //y方向偏移量
  704. xi = -X[2]; //尺度方向偏移量
  705. //如果三个方向偏移量都小于0.5,说明已经找到特征点准确位置
  706. if (abs(xc) < 0.5f && abs(xr) < 0.5f && abs(xi) < 0.5f)
  707. break;
  708. //如果其中一个方向的偏移量过大,则删除该点
  709. if (abs(xc) > (float)(INT_MAX / 3) ||
  710. abs(xr) > (float)(INT_MAX / 3) ||
  711. abs(xi) > (float)(INT_MAX / 3))
  712. return false;
  713. col = col + cvRound(xc);
  714. row = row + cvRound(xr);
  715. layer = layer + cvRound(xi);
  716. //如果特征点定位在边界区域,同样也需要删除
  717. if (layer<1 || layer>nOctaveLayers ||
  718. col < IMG_BORDER || col >= img.cols - IMG_BORDER ||
  719. row < IMG_BORDER || row >= img.rows - IMG_BORDER)
  720. return false;
  721. }
  722. //如果i=MAX_INTERP_STEPS,说明循环结束也没有满足条件,即该特征点需要被删除
  723. if (i >= MAX_INTERP_STEPS)
  724. return false;
  725. /**************************再次删除低响应点(对比度较低的点)********************************/
  726. //再次计算特征点位置x方向,y方向,尺度方向的一阶偏导数
  727. //高对比度的特征对图像的变形是稳定的
  728. const Mat& img = dog_pyr[octave][layer];
  729. const Mat& prev = dog_pyr[octave][layer - 1];
  730. const Mat& next = dog_pyr[octave][layer + 1];
  731. float dx = (img.at<float>(row, col + 1) - img.at<float>(row, col - 1)) * deriv_scale;
  732. float dy = (img.at<float>(row + 1, col) - img.at<float>(row - 1, col)) * deriv_scale;
  733. float dz = (next.at<float>(row, col) - prev.at<float>(row, col)) * deriv_scale;
  734. Matx31f dD(dx, dy, dz);
  735. float t = dD.dot(Matx31f(xc, xr, xi));
  736. float contr = img.at<float>(row, col) + t * 0.5f; //特征点响应 |D(x~)| 即对比度
  737. //Low建议contr阈值是0.03,但是RobHess等建议阈值为0.04/nOctaveLayers
  738. if (abs(contr) < contrastThreshold / nOctaveLayers) //阈值设为0.03时特征点数量过多
  739. return false;
  740. /******************************删除边缘响应比较强的点************************************/
  741. //再次计算特征点位置二阶偏导数,获取特征点出的 Hessian 矩阵,主曲率通过 2X2 的 Hessian 矩阵求出
  742. //一个定义不好的高斯差分算子的极值在横跨边缘的地方有较大的主曲率而在垂直边缘的方向有较小的主曲率
  743. float v2 = (float)img.at<float>(row, col) * 2.f;
  744. float dxx = (img.at<float>(row, col + 1) + img.at<float>(row, col - 1) - v2) * second_deriv_scale;
  745. float dyy = (img.at<float>(row + 1, col) + img.at<float>(row - 1, col) - v2) * second_deriv_scale;
  746. float dxy = (img.at<float>(row + 1, col + 1) + img.at<float>(row - 1, col - 1) -
  747. img.at<float>(row + 1, col - 1) - img.at<float>(row - 1, col + 1)) * cross_deriv_scale;
  748. float det = dxx * dyy - dxy * dxy;
  749. float trace = dxx + dyy;
  750. //主曲率和阈值的对比判定
  751. if (det <= 0 || (trace * trace * edgeThreshold >= det * (edgeThreshold + 1) * (edgeThreshold + 1)))
  752. return false;
  753. /*********保存该特征点信息***********/
  754. kpt.pt.x = ((float)col + xc) * (1 << octave); //高斯金字塔坐标根据组数扩大相应的倍数
  755. kpt.pt.y = ((float)row + xr) * (1 << octave);
  756. // SIFT 描述子
  757. kpt.octave = octave + (layer << 8) + (cvRound((xi + 0.5) * 255) << 16); //特征点被检测出时所在的金字塔组
  758. kpt.size = sigma * powf(2.f, (layer + xi) / nOctaveLayers) * (1 << octave) * 2; //关键点邻域直径
  759. kpt.response = abs(contr); //特征点响应值(对比度)
  760. return true;
  761. }
  762. /************该函数在DOG金字塔上进行特征点检测,特征点精确定位,删除低对比度点,删除边缘响应较大点**********/
  763. /*dog_pyr表示高斯金字塔 原始 SIFT 算子
  764. gauss_pyr表示高斯金字塔
  765. keypoints表示检测到的特征点*/
  766. void mySift::find_scale_space_extrema(const vector<vector<Mat>>& dog_pyr, const vector<vector<Mat>>& gauss_pyr,
  767. vector<KeyPoint>& keypoints)
  768. {
  769. int nOctaves = (int)dog_pyr.size(); //子八度个数
  770. //Low文章建议thresholdThreshold是0.03,Rob Hess等人使用0.04/nOctaveLayers作为阈值
  771. float threshold = (float)(contrastThreshold / nOctaveLayers);
  772. const int n = ORI_HIST_BINS; //n=36
  773. float hist[n];
  774. KeyPoint kpt;
  775. keypoints.clear(); //先清空keypoints
  776. for (int i = 0; i < nOctaves; ++i) //对于每一组
  777. {
  778. for (int j = 1; j <= nOctaveLayers; ++j) //对于组内每一层
  779. {
  780. const Mat& curr_img = dog_pyr[i][j]; //当前层
  781. const Mat& prev_img = dog_pyr[i][j - 1]; //上一层
  782. const Mat& next_img = dog_pyr[i][j + 1]; //下一层
  783. int num_row = curr_img.rows;
  784. int num_col = curr_img.cols; //获得当前组图像的大小
  785. size_t step = curr_img.step1(); //一行元素所占字节数
  786. //遍历每一个尺度层中的有效像素,像素值
  787. for (int r = IMG_BORDER; r < num_row - IMG_BORDER; ++r)
  788. {
  789. const float* curr_ptr = curr_img.ptr<float>(r); //指向的是第 r 行的起点,返回的是 float 类型的像素值
  790. const float* prev_ptr = prev_img.ptr<float>(r - 1);
  791. const float* next_ptr = next_img.ptr<float>(r + 1);
  792. for (int c = IMG_BORDER; c < num_col - IMG_BORDER; ++c)
  793. {
  794. float val = curr_ptr[c]; //当前中心点响应值
  795. //开始检测特征点
  796. if (abs(val) > threshold &&
  797. ((val > 0 && val >= curr_ptr[c - 1] && val >= curr_ptr[c + 1] &&
  798. val >= curr_ptr[c - step - 1] && val >= curr_ptr[c - step] && val >= curr_ptr[c - step + 1] &&
  799. val >= curr_ptr[c + step - 1] && val >= curr_ptr[c + step] && val >= curr_ptr[c + step + 1] &&
  800. val >= prev_ptr[c] && val >= prev_ptr[c - 1] && val >= prev_ptr[c + 1] &&
  801. val >= prev_ptr[c - step - 1] && val >= prev_ptr[c - step] && val >= prev_ptr[c - step + 1] &&
  802. val >= prev_ptr[c + step - 1] && val >= prev_ptr[c + step] && val >= prev_ptr[c + step + 1] &&
  803. val >= next_ptr[c] && val >= next_ptr[c - 1] && val >= next_ptr[c + 1] &&
  804. val >= next_ptr[c - step - 1] && val >= next_ptr[c - step] && val >= next_ptr[c - step + 1] &&
  805. val >= next_ptr[c + step - 1] && val >= next_ptr[c + step] && val >= next_ptr[c + step + 1]) ||
  806. (val < 0 && val <= curr_ptr[c - 1] && val <= curr_ptr[c + 1] &&
  807. val <= curr_ptr[c - step - 1] && val <= curr_ptr[c - step] && val <= curr_ptr[c - step + 1] &&
  808. val <= curr_ptr[c + step - 1] && val <= curr_ptr[c + step] && val <= curr_ptr[c + step + 1] &&
  809. val <= prev_ptr[c] && val <= prev_ptr[c - 1] && val <= prev_ptr[c + 1] &&
  810. val <= prev_ptr[c - step - 1] && val <= prev_ptr[c - step] && val <= prev_ptr[c - step + 1] &&
  811. val <= prev_ptr[c + step - 1] && val <= prev_ptr[c + step] && val <= prev_ptr[c + step + 1] &&
  812. val <= next_ptr[c] && val <= next_ptr[c - 1] && val <= next_ptr[c + 1] &&
  813. val <= next_ptr[c - step - 1] && val <= next_ptr[c - step] && val <= next_ptr[c - step + 1] &&
  814. val <= next_ptr[c + step - 1] && val <= next_ptr[c + step] && val <= next_ptr[c + step + 1])))
  815. {
  816. //++numKeys;
  817. //获得特征点初始行号,列号,组号,组内层号
  818. int octave = i, layer = j, r1 = r, c1 = c;
  819. if (!adjust_local_extrema_1(dog_pyr, kpt, octave, layer, r1, c1,
  820. nOctaveLayers, (float)contrastThreshold,
  821. (float)edgeThreshold, (float)sigma))
  822. {
  823. continue; //如果该初始点不满足条件,则不保存改点
  824. }
  825. float scale = kpt.size / float(1 << octave); //该特征点相对于本组的尺度
  826. //max_hist值对应的方向为主方向
  827. float max_hist = clac_orientation_hist(gauss_pyr[octave][layer], Point(c1, r1), scale, n, hist);
  828. //大于mag_thr值对应的方向为辅助方向
  829. float mag_thr = max_hist * ORI_PEAK_RATIO; //主峰值 80% 的方向作为辅助方向
  830. //遍历直方图中的 36 个bin
  831. for (int i = 0; i < n; ++i)
  832. {
  833. int left = i > 0 ? i - 1 : n - 1;
  834. int right = i < n - 1 ? i + 1 : 0;
  835. //创建新的特征点,大于主峰值 80% 的方向,赋值给该特征点,作为一个新的特征点;即有多个特征点,位置、尺度相同,方向不同
  836. if (hist[i] > hist[left] && hist[i] > hist[right] && hist[i] >= mag_thr)
  837. {
  838. float bin = i + 0.5f * (hist[left] - hist[right]) / (hist[left] + hist[right] - 2 * hist[i]);
  839. bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;
  840. kpt.angle = (360.f / n) * bin; //原始 SIFT 算子使用的特征点的主方向0-360度
  841. keypoints.push_back(kpt); //保存该特征点
  842. }
  843. }
  844. }
  845. }
  846. }
  847. }
  848. }
  849. //cout << "初始满足要求特征点个数是: " << numKeys << endl;
  850. }
  851. /************该函数在DOG金字塔上进行特征点检测,特征点精确定位,删除低对比度点,删除边缘响应较大点**********/
  852. //对特征点进行方向的细化 + 增加更多的主方向版本 ——此时细化是对最后要给关键点进行赋值时的细化
  853. //还可以考虑直接对方向直方图进行细化
  854. void mySift::find_scale_space_extrema1(const vector<vector<Mat>>& dog_pyr, vector<vector<Mat>>& gauss_pyr,
  855. vector<KeyPoint>& keypoints)
  856. {
  857. int nOctaves = (int)dog_pyr.size(); //子八度个数
  858. //Low文章建议thresholdThreshold是0.03,Rob Hess等人使用0.04/nOctaveLayers作为阈值
  859. float threshold = (float)(contrastThreshold / nOctaveLayers);
  860. const int n = ORI_HIST_BINS; //n=36
  861. float hist[n];
  862. KeyPoint kpt;
  863. vector<Mat> amplit; //存放高斯差分金字塔每一层的梯度幅度图像
  864. vector<Mat> orient; //存放高斯差分金字塔每一层的梯度方向图像
  865. keypoints.clear(); //先清空keypoints
  866. for (int i = 0; i < nOctaves; ++i) //对于每一组
  867. {
  868. for (int j = 1; j <= nOctaveLayers; ++j) //对于组内每一层
  869. {
  870. const Mat& curr_img = dog_pyr[i][j]; //当前层
  871. const Mat& prev_img = dog_pyr[i][j - 1]; //上一层
  872. const Mat& next_img = dog_pyr[i][j + 1]; //下一层
  873. int num_row = curr_img.rows;
  874. int num_col = curr_img.cols; //获得当前组图像的大小
  875. size_t step = curr_img.step1(); //一行元素所占字节数
  876. //遍历每一个尺度层中的有效像素,像素值
  877. for (int r = IMG_BORDER; r < num_row - IMG_BORDER; ++r)
  878. {
  879. const float* curr_ptr = curr_img.ptr<float>(r); //指向的是第 r 行的起点,返回的是 float 类型的像素值
  880. const float* prev_ptr = prev_img.ptr<float>(r);
  881. const float* next_ptr = next_img.ptr<float>(r);
  882. for (int c = IMG_BORDER; c < num_col - IMG_BORDER; ++c)
  883. {
  884. float val = curr_ptr[c]; //当前中心点响应值
  885. //开始检测特征点
  886. if (abs(val) > threshold &&
  887. ((val > 0 && val >= curr_ptr[c - 1] && val >= curr_ptr[c + 1] &&
  888. val >= curr_ptr[c - step - 1] && val >= curr_ptr[c - step] && val >= curr_ptr[c - step + 1] &&
  889. val >= curr_ptr[c + step - 1] && val >= curr_ptr[c + step] && val >= curr_ptr[c + step + 1] &&
  890. val >= prev_ptr[c] && val >= prev_ptr[c - 1] && val >= prev_ptr[c + 1] &&
  891. val >= prev_ptr[c - step - 1] && val >= prev_ptr[c - step] && val >= prev_ptr[c - step + 1] &&
  892. val >= prev_ptr[c + step - 1] && val >= prev_ptr[c + step] && val >= prev_ptr[c + step + 1] &&
  893. val >= next_ptr[c] && val >= next_ptr[c - 1] && val >= next_ptr[c + 1] &&
  894. val >= next_ptr[c - step - 1] && val >= next_ptr[c - step] && val >= next_ptr[c - step + 1] &&
  895. val >= next_ptr[c + step - 1] && val >= next_ptr[c + step] && val >= next_ptr[c + step + 1]) ||
  896. (val < 0 && val <= curr_ptr[c - 1] && val <= curr_ptr[c + 1] &&
  897. val <= curr_ptr[c - step - 1] && val <= curr_ptr[c - step] && val <= curr_ptr[c - step + 1] &&
  898. val <= curr_ptr[c + step - 1] && val <= curr_ptr[c + step] && val <= curr_ptr[c + step + 1] &&
  899. val <= prev_ptr[c] && val <= prev_ptr[c - 1] && val <= prev_ptr[c + 1] &&
  900. val <= prev_ptr[c - step - 1] && val <= prev_ptr[c - step] && val <= prev_ptr[c - step + 1] &&
  901. val <= prev_ptr[c + step - 1] && val <= prev_ptr[c + step] && val <= prev_ptr[c + step + 1] &&
  902. val <= next_ptr[c] && val <= next_ptr[c - 1] && val <= next_ptr[c + 1] &&
  903. val <= next_ptr[c - step - 1] && val <= next_ptr[c - step] && val <= next_ptr[c - step + 1] &&
  904. val <= next_ptr[c + step - 1] && val <= next_ptr[c + step] && val <= next_ptr[c + step + 1])))
  905. {
  906. //++numKeys;
  907. //获得特征点初始行号,列号,组号,组内层号
  908. int octave = i, layer = j, r1 = r, c1 = c, nums = i * nOctaves + j;
  909. if (!adjust_local_extrema_2(dog_pyr, kpt, octave, layer, r1, c1,
  910. nOctaveLayers, (float)contrastThreshold,
  911. (float)edgeThreshold, (float)sigma))
  912. {
  913. continue; //如果该初始点不满足条件,则不保存改点
  914. }
  915. float scale = kpt.size / float(1 << octave); //该特征点相对于本组的尺度
  916. //计算梯度幅度和梯度方向
  917. //amplit_orient(curr_img, amplit, orient, scale, nums);
  918. //max_hist值对应的方向为主方向
  919. float max_hist = clac_orientation_hist(gauss_pyr[octave][layer], Point(c1, r1), scale, n, hist);
  920. //float max_hist = calc_orient_hist(amplit[nums], orient[nums], Point2f(c1, r1), scale, hist, n);
  921. 大于mag_thr值对应的方向为辅助方向
  922. //float mag_thr = max_hist * ORI_PEAK_RATIO; //主峰值 80% 的方向作为辅助方向
  923. //增加更多的主方向,以增加特征点对梯度差异的鲁棒性
  924. float sum = 0.0; //直方图对应的幅值之和
  925. float mag_thr = 0.0; //判断是否为主方向的阈值
  926. for (int i = 0; i < n; ++i)
  927. {
  928. sum += hist[i];
  929. }
  930. mag_thr = 0.5 * (1.0 / 36) * sum;
  931. //遍历直方图中的 36 个bin
  932. for (int i = 0; i < n; ++i)
  933. {
  934. int left = i > 0 ? i - 1 : n - 1;
  935. int right = i < n - 1 ? i + 1 : 0;
  936. //创建新的特征点,大于主峰值 80% 的方向,赋值给该特征点,作为一个新的特征点;即有多个特征点,位置、尺度相同,方向不同
  937. if (hist[i] > hist[left] && hist[i] > hist[right] && hist[i] >= mag_thr)
  938. {
  939. float bin = i + 0.5f * (hist[left] - hist[right]) / (hist[left] + hist[right] - 2 * hist[i]);
  940. bin = bin < 0 ? n + bin : bin >= n ? bin - n : bin;
  941. //修改的地方,特征点的主方向修改为了0-180度,相当于对方向做了一个细化
  942. float angle = (360.f / n) * bin;
  943. if (angle >= 1 && angle <= 180)
  944. {
  945. kpt.angle = angle;
  946. }
  947. else if (angle > 180 && angle < 360)
  948. {
  949. kpt.angle = 360 - angle;
  950. }
  951. //kpt.angle = (360.f / n) * bin; //原始 SIFT 算子使用的特征点的主方向0-360度
  952. keypoints.push_back(kpt); //保存该特征点
  953. }
  954. }
  955. }
  956. }
  957. }
  958. }
  959. }
  960. //cout << "初始满足要求特征点个数是: " << numKeys << endl;
  961. }
  962. /*该函数生成matlab中的meshgrid函数*/
  963. /*x_range表示x方向的范围
  964. y_range表示y方向的范围
  965. X表示生成的沿x轴变化的网格
  966. Y表示生成沿y轴变换的网格
  967. */
  968. static void meshgrid(const Range& x_range, const Range& y_range, Mat& X, Mat& Y)
  969. {
  970. int x_start = x_range.start, x_end = x_range.end;
  971. int y_start = y_range.start, y_end = y_range.end;
  972. int width = x_end - x_start + 1;
  973. int height = y_end - y_start + 1;
  974. X.create(height, width, CV_32FC1);
  975. Y.create(height, width, CV_32FC1);
  976. for (int i = y_start; i <= y_end; i++)
  977. {
  978. float* ptr_1 = X.ptr<float>(i - y_start);
  979. for (int j = x_start; j <= x_end; ++j)
  980. ptr_1[j - x_start] = j * 1.0f;
  981. }
  982. for (int i = y_start; i <= y_end; i++)
  983. {
  984. float* ptr_2 = Y.ptr<float>(i - y_start);
  985. for (int j = x_start; j <= x_end; ++j)
  986. ptr_2[j - x_start] = i * 1.0f;
  987. }
  988. }
  989. /******************************计算一个特征点的描述子***********************************/
  990. /*gauss_image表示特征点所在的高斯层
  991. main_angle表示特征点的主方向,角度范围是0-360度
  992. pt表示特征点在高斯图像上的坐标,相对与本组,不是相对于最底层
  993. scale表示特征点所在层的尺度,相对于本组,不是相对于最底层
  994. d表示特征点邻域网格宽度
  995. n表示每个网格内像素梯度角度等分个数
  996. descriptor表示生成的特征点的描述子*/
  997. static void calc_sift_descriptor(const Mat& gauss_image, float main_angle, Point2f pt,
  998. float scale, int d, int n, float* descriptor)
  999. {
  1000. Point ptxy(cvRound(pt.x), cvRound(pt.y)); //坐标取整
  1001. float cos_t = cosf(-main_angle * (float)(CV_PI / 180)); //把角度转化为弧度,计算主方向的余弦
  1002. float sin_t = sinf(-main_angle * (float)(CV_PI / 180)); //把角度转化为弧度,计算主方向的正弦
  1003. float bins_per_rad = n / 360.f; // n = 8 ,梯度直方图分为 8 个方向
  1004. float exp_scale = -1.f / (d * d * 0.5f); //权重指数部分
  1005. float hist_width = DESCR_SCL_FCTR * scale; //特征点邻域内子区域边长,子区域的边长
  1006. int radius = cvRound(hist_width * (d + 1) * sqrt(2) * 0.5f);//特征点邻域半径(d+1)*(d+1),四舍五入
  1007. int rows = gauss_image.rows, cols = gauss_image.cols; //当前高斯层行、列信息
  1008. //特征点邻域半径
  1009. radius = min(radius, (int)sqrt((double)rows * rows + cols * cols));
  1010. cos_t = cos_t / hist_width;
  1011. sin_t = sin_t / hist_width;
  1012. int len = (2 * radius + 1) * (2 * radius + 1); //邻域内总像素数,为后面动态分配内存使用
  1013. int histlen = (d + 2) * (d + 2) * (n + 2); //值为 360
  1014. AutoBuffer<float> buf(6 * len + histlen);
  1015. //X保存水平差分,Y保存竖直差分,Mag保存梯度幅度,Angle保存特征点方向, W保存高斯权重
  1016. float* X = buf, * Y = buf + len, * Mag = Y, * Angle = Y + len, * W = Angle + len;
  1017. float* RBin = W + len, * CBin = RBin + len, * hist = CBin + len;
  1018. //首先清空直方图数据
  1019. for (int i = 0; i < d + 2; ++i) // i 对应 row
  1020. {
  1021. for (int j = 0; j < d + 2; ++j) // j 对应 col
  1022. {
  1023. for (int k = 0; k < n + 2; ++k)
  1024. hist[(i * (d + 2) + j) * (n + 2) + k] = 0.f;
  1025. }
  1026. }
  1027. //把邻域内的像素分配到相应子区域内,计算子区域内每个像素点的权重(子区域即 d*d 中每一个小方格)
  1028. int k = 0;
  1029. //实际上是在 4 x 4 的网格中找 16 个种子点,每个种子点都在子网格的正中心,
  1030. //通过三线性插值对不同种子点间的像素点进行加权作用到不同的种子点上绘制方向直方图
  1031. for (int i = -radius; i < radius; ++i) // i 对应 y 行坐标
  1032. {
  1033. for (int j = -radius; j < radius; ++j) // j 对应 x 列坐标
  1034. {
  1035. float c_rot = j * cos_t - i * sin_t; //旋转后邻域内采样点的 x 坐标
  1036. float r_rot = j * sin_t + i * cos_t; //旋转后邻域内采样点的 y 坐标
  1037. //旋转后 5 x 5 的网格中的所有像素点被分配到 4 x 4 的网格中
  1038. float cbin = c_rot + d / 2 - 0.5f; //旋转后的采样点落在子区域的 x 坐标
  1039. float rbin = r_rot + d / 2 - 0.5f; //旋转后的采样点落在子区域的 y 坐标
  1040. int r = ptxy.y + i, c = ptxy.x + j; //ptxy是高斯金字塔中的坐标
  1041. //这里rbin,cbin范围是(-1,d)
  1042. if (rbin > -1 && rbin < d && cbin>-1 && cbin < d && r>0 && r < rows - 1 && c>0 && c < cols - 1)
  1043. {
  1044. float dx = gauss_image.at<float>(r, c + 1) - gauss_image.at<float>(r, c - 1);
  1045. float dy = gauss_image.at<float>(r + 1, c) - gauss_image.at<float>(r - 1, c);
  1046. X[k] = dx; //邻域内所有像素点的水平差分
  1047. Y[k] = dy; //邻域内所有像素点的竖直差分
  1048. CBin[k] = cbin; //邻域内所有采样点落在子区域的 x 坐标
  1049. RBin[k] = rbin; //邻域内所有采样点落在子区域的 y 坐标
  1050. W[k] = (c_rot * c_rot + r_rot * r_rot) * exp_scale; //高斯权值的指数部分
  1051. ++k;
  1052. }
  1053. }
  1054. }
  1055. //计算采样点落在子区域的像素梯度幅度,梯度角度,和高斯权值
  1056. len = k;
  1057. cv::hal::exp(W, W, len); //邻域内所有采样点落在子区域的像素的高斯权值
  1058. cv::hal::fastAtan2(Y, X, Angle, len, true); //邻域内所有采样点落在子区域的像素的梯度方向,角度范围是0-360度
  1059. cv::hal::magnitude(X, Y, Mag, len); //邻域内所有采样点落在子区域的像素的梯度幅度
  1060. //实际上是在 4 x 4 的网格中找 16 个种子点,每个种子点都在子网格的正中心,
  1061. //通过三线性插值对不同种子点间的像素点进行加权作用到不同的种子点上绘制方向直方图
  1062. //计算每个特征点的特征描述子
  1063. for (k = 0; k < len; ++k)
  1064. {
  1065. float rbin = RBin[k], cbin = CBin[k]; //子区域内像素点坐标,rbin,cbin范围是(-1,d)
  1066. 改进的地方,对方向进行了一个细化,也是为了增加对梯度差异的鲁棒性
  1067. //if (Angle[k] > 180 && Angle[k] < 360)
  1068. // Angle[k] = 360 - Angle[k];
  1069. //子区域内像素点处理后的方向
  1070. float temp = Angle[k] - main_angle;
  1071. /*if (temp > 180 && temp < 360)
  1072. temp = 360 - temp;*/
  1073. float obin = temp * bins_per_rad; //指定方向的数量后,邻域内像素点对应的方向
  1074. float mag = Mag[k] * W[k]; //子区域内像素点乘以权值后的梯度幅值
  1075. int r0 = cvFloor(rbin); //ro取值集合是{-1,0,1,2,3},没太懂为什么?
  1076. int c0 = cvFloor(cbin); //c0取值集合是{-1,0,1,2,3}
  1077. int o0 = cvFloor(obin);
  1078. rbin = rbin - r0; //子区域内像素点坐标的小数部分,用于线性插值,分配像素点的作用
  1079. cbin = cbin - c0;
  1080. obin = obin - o0; //子区域方向的小数部分
  1081. //限制范围为梯度直方图横坐标[0,n),8 个方向直方图
  1082. if (o0 < 0)
  1083. o0 = o0 + n;
  1084. if (o0 >= n)
  1085. o0 = o0 - n;
  1086. //三线性插值用于计算落在两个子区域之间的像素对两个子区域的作用,并把其分配到对应子区域的8个方向上
  1087. //像素对应的信息通过加权分配给其周围的种子点,并把相应方向的梯度值进行累加
  1088. float v_r1 = mag * rbin; //第二行分配的值
  1089. float v_r0 = mag - v_r1; //第一行分配的值
  1090. float v_rc11 = v_r1 * cbin; //第二行第二列分配的值,右下角种子点
  1091. float v_rc10 = v_r1 - v_rc11; //第二行第一列分配的值,左下角种子点
  1092. float v_rc01 = v_r0 * cbin; //第一行第二列分配的值,右上角种子点
  1093. float v_rc00 = v_r0 - v_rc01; //第一行第一列分配的值,左上角种子点
  1094. //一个像素点的方向为每个种子点的两个方向做出贡献
  1095. float v_rco111 = v_rc11 * obin; //右下角种子点第二个方向上分配的值
  1096. float v_rco110 = v_rc11 - v_rco111; //右下角种子点第一个方向上分配的值
  1097. float v_rco101 = v_rc10 * obin;
  1098. float v_rco100 = v_rc10 - v_rco101;
  1099. float v_rco011 = v_rc01 * obin;
  1100. float v_rco010 = v_rc01 - v_rco011;
  1101. float v_rco001 = v_rc00 * obin;
  1102. float v_rco000 = v_rc00 - v_rco001;
  1103. //该像素所在网格的索引
  1104. int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n + 2) + o0;
  1105. hist[idx] += v_rco000;
  1106. hist[idx + 1] += v_rco001;
  1107. hist[idx + n + 2] += v_rco010;
  1108. hist[idx + n + 3] += v_rco011;
  1109. hist[idx + (d + 2) * (n + 2)] += v_rco100;
  1110. hist[idx + (d + 2) * (n + 2) + 1] += v_rco101;
  1111. hist[idx + (d + 3) * (n + 2)] += v_rco110;
  1112. hist[idx + (d + 3) * (n + 2) + 1] += v_rco111;
  1113. }
  1114. //由于圆周循环的特性,对计算以后幅角小于 0 度或大于 360 度的值重新进行调整,使
  1115. //其在 0~360 度之间
  1116. for (int i = 0; i < d; ++i)
  1117. {
  1118. for (int j = 0; j < d; ++j)
  1119. {
  1120. //类似于 hist[0][2][3] 第 0 行,第 2 列,种子点直方图中的第 3 个 bin
  1121. int idx = ((i + 1) * (d + 2) + (j + 1)) * (n + 2);
  1122. hist[idx] += hist[idx + n];
  1123. //hist[idx + 1] += hist[idx + n + 1];//opencv源码中这句话是多余的,hist[idx + n + 1]永远是0.0
  1124. for (k = 0; k < n; ++k)
  1125. descriptor[(i * d + j) * n + k] = hist[idx + k];
  1126. }
  1127. }
  1128. //对描述子进行归一化
  1129. int lenght = d * d * n;
  1130. float norm = 0;
  1131. //计算特征描述向量的模值的平方
  1132. for (int i = 0; i < lenght; ++i)
  1133. {
  1134. norm = norm + descriptor[i] * descriptor[i];
  1135. }
  1136. norm = sqrt(norm); //特征描述向量的模值
  1137. //此次归一化能去除光照的影响
  1138. for (int i = 0; i < lenght; ++i)
  1139. {
  1140. descriptor[i] = descriptor[i] / norm;
  1141. }
  1142. //阈值截断,去除特征描述向量中大于 0.2 的值,能消除非线性光照的影响(相机饱和度对某些放的梯度影响较大,对方向的影响较小)
  1143. for (int i = 0; i < lenght; ++i)
  1144. {
  1145. descriptor[i] = min(descriptor[i], DESCR_MAG_THR);
  1146. }
  1147. //再次归一化,能够提高特征的独特性
  1148. norm = 0;
  1149. for (int i = 0; i < lenght; ++i)
  1150. {
  1151. norm = norm + descriptor[i] * descriptor[i];
  1152. }
  1153. norm = sqrt(norm);
  1154. for (int i = 0; i < lenght; ++i)
  1155. {
  1156. descriptor[i] = descriptor[i] / norm;
  1157. }
  1158. }
  1159. /*************************该函数计算每个特征点的特征描述子*****************************/
  1160. /*amplit表示特征点所在层的梯度幅度图像
  1161. orient表示特征点所在层的梯度角度图像
  1162. pt表示特征点的位置
  1163. scale表示特征点所在层的尺度
  1164. main_ori表示特征点的主方向,0-360度
  1165. d表示GLOH角度方向区间个数,默认是8,
  1166. n表示每个网格内角度在0-360度之间等分个数,n默认是8
  1167. */
  1168. static void calc_gloh_descriptor(const Mat& amplit, const Mat& orient, Point2f pt, float scale, float main_ori, int d, int n, float* ptr_des)
  1169. {
  1170. Point point(cvRound(pt.x), cvRound(pt.y));
  1171. //特征点旋转方向余弦和正弦
  1172. float cos_t = cosf(-main_ori / 180.f * (float)CV_PI);
  1173. float sin_t = sinf(-main_ori / 180.f * (float)CV_PI);
  1174. int num_rows = amplit.rows;
  1175. int num_cols = amplit.cols;
  1176. int radius = cvRound(SAR_SIFT_RADIUS_DES * scale);
  1177. radius = min(radius, min(num_rows / 2, num_cols / 2));//特征点邻域半径
  1178. int radius_x_left = point.x - radius;
  1179. int radius_x_right = point.x + radius;
  1180. int radius_y_up = point.y - radius;
  1181. int radius_y_down = point.y + radius;
  1182. //防止越界
  1183. if (radius_x_left < 0)
  1184. radius_x_left = 0;
  1185. if (radius_x_right > num_cols - 1)
  1186. radius_x_right = num_cols - 1;
  1187. if (radius_y_up < 0)
  1188. radius_y_up = 0;
  1189. if (radius_y_down > num_rows - 1)
  1190. radius_y_down = num_rows - 1;
  1191. //此时特征点周围本矩形区域的中心,相对于该矩形
  1192. int center_x = point.x - radius_x_left;
  1193. int center_y = point.y - radius_y_up;
  1194. //特征点周围区域内像素梯度幅度,梯度角度
  1195. Mat sub_amplit = amplit(Range(radius_y_up, radius_y_down + 1), Range(radius_x_left, radius_x_right + 1));
  1196. Mat sub_orient = orient(Range(radius_y_up, radius_y_down + 1), Range(radius_x_left, radius_x_right + 1));
  1197. //以center_x和center_y位中心,对下面矩形区域进行旋转
  1198. Range x_rng(-(point.x - radius_x_left), radius_x_right - point.x);
  1199. Range y_rng(-(point.y - radius_y_up), radius_y_down - point.y);
  1200. Mat X, Y;
  1201. meshgrid(x_rng, y_rng, X, Y);
  1202. Mat c_rot = X * cos_t - Y * sin_t;
  1203. Mat r_rot = X * sin_t + Y * cos_t;
  1204. Mat GLOH_angle, GLOH_amplit;
  1205. phase(c_rot, r_rot, GLOH_angle, true);//角度在0-360度之间
  1206. GLOH_amplit = c_rot.mul(c_rot) + r_rot.mul(r_rot);//为了加快速度,没有计算开方
  1207. //三个圆半径平方
  1208. float R1_pow = (float)radius * radius;//外圆半径平方
  1209. float R2_pow = pow(radius * SAR_SIFT_GLOH_RATIO_R1_R2, 2.f);//中间圆半径平方
  1210. float R3_pow = pow(radius * SAR_SIFT_GLOH_RATIO_R1_R3, 2.f);//内圆半径平方
  1211. int sub_rows = sub_amplit.rows;
  1212. int sub_cols = sub_amplit.cols;
  1213. //开始构建描述子,在角度方向对描述子进行插值
  1214. int len = (d * 2 + 1) * n;
  1215. AutoBuffer<float> hist(len);
  1216. for (int i = 0; i < len; ++i)//清零
  1217. hist[i] = 0;
  1218. for (int i = 0; i < sub_rows; ++i)
  1219. {
  1220. float* ptr_amplit = sub_amplit.ptr<float>(i);
  1221. float* ptr_orient = sub_orient.ptr<float>(i);
  1222. float* ptr_GLOH_amp = GLOH_amplit.ptr<float>(i);
  1223. float* ptr_GLOH_ang = GLOH_angle.ptr<float>(i);
  1224. for (int j = 0; j < sub_cols; ++j)
  1225. {
  1226. if (((i - center_y) * (i - center_y) + (j - center_x) * (j - center_x)) < radius * radius)
  1227. {
  1228. float pix_amplit = ptr_amplit[j];//该像素的梯度幅度
  1229. float pix_orient = ptr_orient[j];//该像素的梯度方向
  1230. float pix_GLOH_amp = ptr_GLOH_amp[j];//该像素在GLOH网格中的半径位置
  1231. float pix_GLOH_ang = ptr_GLOH_ang[j];//该像素在GLOH网格中的位置方向
  1232. int rbin, cbin, obin;
  1233. rbin = pix_GLOH_amp < R3_pow ? 0 : (pix_GLOH_amp > R2_pow ? 2 : 1);//rbin={0,1,2}
  1234. cbin = cvRound(pix_GLOH_ang * d / 360.f);
  1235. cbin = cbin > d ? cbin - d : (cbin <= 0 ? cbin + d : cbin);//cbin=[1,d]
  1236. obin = cvRound(pix_orient * n / 360.f);
  1237. obin = obin > n ? obin - n : (obin <= 0 ? obin + n : obin);//obin=[1,n]
  1238. if (rbin == 0)//内圆
  1239. hist[obin - 1] += pix_amplit;
  1240. else
  1241. {
  1242. int idx = ((rbin - 1) * d + cbin - 1) * n + n + obin - 1;
  1243. hist[idx] += pix_amplit;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. //对描述子进行归一化
  1249. float norm = 0;
  1250. for (int i = 0; i < len; ++i)
  1251. {
  1252. norm = norm + hist[i] * hist[i];
  1253. }
  1254. norm = sqrt(norm);
  1255. for (int i = 0; i < len; ++i)
  1256. {
  1257. hist[i] = hist[i] / norm;
  1258. }
  1259. //阈值截断
  1260. for (int i = 0; i < len; ++i)
  1261. {
  1262. hist[i] = min(hist[i], DESCR_MAG_THR);
  1263. }
  1264. //再次归一化
  1265. norm = 0;
  1266. for (int i = 0; i < len; ++i)
  1267. {
  1268. norm = norm + hist[i] * hist[i];
  1269. }
  1270. norm = sqrt(norm);
  1271. for (int i = 0; i < len; ++i)
  1272. {
  1273. ptr_des[i] = hist[i] / norm;
  1274. }
  1275. }
  1276. /******************************计算一个特征点的描述子—改进版***********************************/
  1277. static void improve_calc_sift_descriptor(const Mat& gauss_image, float main_angle, Point2f pt,
  1278. float scale, int d, int n, float* descriptor)
  1279. {
  1280. int n1 = 16, n2 = 6, n3 = 4;
  1281. Point ptxy(cvRound(pt.x), cvRound(pt.y)); //坐标取整
  1282. float cos_t = cosf(-main_angle * (float)(CV_PI / 180)); //计算主方向的余弦
  1283. float sin_t = sinf(-main_angle * (float)(CV_PI / 180)); //计算主方向的正弦
  1284. float bin_per_rad_1 = n1 / 360.f; //n=8
  1285. float bin_per_rad_2 = n2 / 360.f; //原理特征点部分阈值
  1286. float bin_per_rad_3 = n3 / 360.f; //原理特征点部分阈值
  1287. float exp_scale = -1.f / (d * d * 0.5f); //权重指数部分
  1288. float hist_width = DESCR_SCL_FCTR * scale; //子区域边长,子区域的面积也即采样像素点个数
  1289. int radius = cvRound(hist_width * (d + 1) * sqrt(2) * 0.5f);//特征点邻域半径(d+1)*(d+1)
  1290. int rows = gauss_image.rows, cols = gauss_image.cols;
  1291. //特征点邻域半径
  1292. radius = min(radius, (int)sqrt((double)rows * rows + cols * cols));
  1293. cos_t = cos_t / hist_width;
  1294. sin_t = sin_t / hist_width;
  1295. int len = (2 * radius + 1) * (2 * radius + 1); //邻域内总像素数
  1296. int histlen = (d + 2) * (d + 2) * (n1 + 2);
  1297. AutoBuffer<float> buf(6 * len + histlen);
  1298. //X保存水平差分,Y保存竖直差分,Mag保存梯度幅度,Angle保存特征点方向, W保存高斯权重
  1299. float* X = buf, * Y = buf + len, * Mag = Y, * Angle = Y + len, * W = Angle + len;
  1300. float* X2 = buf, * Y2 = buf + len, * Mag2 = Y, * Angle2 = Y + len, * W2 = Angle + len;
  1301. float* X3 = buf, * Y3 = buf + len, * Mag3 = Y, * Angle3 = Y + len, * W3 = Angle + len;
  1302. float* RBin = W + len, * CBin = RBin + len, * hist = CBin + len;
  1303. float* RBin2 = W + len, * CBin2 = RBin + len;
  1304. float* RBin3 = W + len, * CBin3 = RBin + len;
  1305. //首先清空直方图数据
  1306. for (int i = 0; i < d + 2; ++i)
  1307. {
  1308. for (int j = 0; j < d + 2; ++j)
  1309. {
  1310. for (int k = 0; k < n + 2; ++k)
  1311. hist[(i * (d + 2) + j) * (n + 2) + k] = 0.f;
  1312. }
  1313. }
  1314. //把邻域内的像素分配到相应子区域内,计算子区域内每个像素点的权重(子区域即 d*d 中每一个小方格)
  1315. int k1 = 0, k2 = 0, k3 = 0;
  1316. vector<int> v; //存放外邻域像素点对应的序号
  1317. for (int i = -radius; i < radius; ++i)
  1318. {
  1319. for (int j = -radius; j < radius; ++j)
  1320. {
  1321. float c_rot = j * cos_t - i * sin_t; //旋转后邻域内采样点的 x 坐标
  1322. float r_rot = j * sin_t + i * cos_t; //旋转后邻域内采样点的 y 坐标
  1323. float rbin = r_rot + d / 2 - 0.5f; //旋转后的采样点落在子区域的 y 坐标
  1324. float cbin = c_rot + d / 2 - 0.5f; //旋转后的采样点落在子区域的 x 坐标
  1325. int r = ptxy.y + i, c = ptxy.x + j; //ptxy是高斯金字塔中的坐标
  1326. //对离中心点近的部分进行操作
  1327. if (abs(i) < (radius / 3) && abs(j) < (radius / 3))
  1328. {
  1329. //这里rbin,cbin范围是(-1,d)
  1330. if (rbin > -1 && rbin < d && cbin>-1 && cbin < d &&
  1331. r>0 && r < rows - 1 && c>0 && c < cols - 1)
  1332. {
  1333. float dx = gauss_image.at<float>(r, c + 1) - gauss_image.at<float>(r, c - 1);
  1334. float dy = gauss_image.at<float>(r + 1, c) - gauss_image.at<float>(r - 1, c);
  1335. X[k1] = dx; //邻域内所有像素点的水平差分
  1336. Y[k1] = dy; //邻域内所有像素点的竖直差分
  1337. RBin[k1] = rbin; //邻域内所有采样点落在子区域的 y 坐标
  1338. CBin[k1] = cbin; //邻域内所有采样点落在子区域的 x 坐标
  1339. //高斯权值的指数部分
  1340. W[k1] = (c_rot * c_rot + r_rot * r_rot) * exp_scale;
  1341. ++k1;
  1342. }
  1343. }
  1344. //对离中心点远的部分进行操作
  1345. else if (abs(i) < (2 * radius / 3) && abs(i) > (radius / 3) && abs(j) < (2 * radius / 3) && abs(j) > (radius / 3))
  1346. {
  1347. //这里rbin,cbin范围是(-1,d)
  1348. if (rbin > -1 && rbin < d && cbin>-1 && cbin < d &&
  1349. r>0 && r < rows - 1 && c>0 && c < cols - 1)
  1350. {
  1351. float dx = gauss_image.at<float>(r, c + 1) - gauss_image.at<float>(r, c - 1);
  1352. float dy = gauss_image.at<float>(r + 1, c) - gauss_image.at<float>(r - 1, c);
  1353. X2[k2] = dx; //邻域内所有像素点的水平差分
  1354. Y2[k2] = dy; //邻域内所有像素点的竖直差分
  1355. RBin2[k2] = rbin; //邻域内所有采样点落在子区域的 y 坐标
  1356. CBin2[k2] = cbin; //邻域内所有采样点落在子区域的 x 坐标
  1357. //高斯权值的指数部分
  1358. W2[k2] = (c_rot * c_rot + r_rot * r_rot) * exp_scale;
  1359. ++k2;
  1360. }
  1361. }
  1362. else
  1363. {
  1364. //这里rbin,cbin范围是(-1,d)
  1365. if (rbin > -1 && rbin < d && cbin>-1 && cbin < d &&
  1366. r>0 && r < rows - 1 && c>0 && c < cols - 1)
  1367. {
  1368. float dx = gauss_image.at<float>(r, c + 1) - gauss_image.at<float>(r, c - 1);
  1369. float dy = gauss_image.at<float>(r + 1, c) - gauss_image.at<float>(r - 1, c);
  1370. X3[k3] = dx; //邻域内所有像素点的水平差分
  1371. Y3[k3] = dy; //邻域内所有像素点的竖直差分
  1372. RBin3[k3] = rbin; //邻域内所有采样点落在子区域的 y 坐标
  1373. CBin3[k3] = cbin; //邻域内所有采样点落在子区域的 x 坐标
  1374. //高斯权值的指数部分
  1375. W3[k3] = (c_rot * c_rot + r_rot * r_rot) * exp_scale;
  1376. ++k3;
  1377. }
  1378. }
  1379. }
  1380. }
  1381. //两个区域内数组的合并拼接
  1382. for (int k = 0; k < k2; k++)
  1383. {
  1384. X[k1 + k] = X2[k];
  1385. Y[k1 + k] = Y2[k];
  1386. RBin[k1 + k] = RBin2[k];
  1387. CBin[k1 + k] = CBin2[k];
  1388. W[k1 + k] = W2[k];
  1389. }
  1390. for (int k = 0; k < k3; k++)
  1391. {
  1392. X[k1 + k2 + k] = X3[k];
  1393. Y[k1 + k2 + k] = Y3[k];
  1394. RBin[k1 + k2 + k] = RBin3[k];
  1395. CBin[k1 + k2 + k] = CBin3[k];
  1396. W[k1 + k2 + k] = W3[k];
  1397. }
  1398. //计算采样点落在子区域的像素梯度幅度,梯度角度,和高斯权值
  1399. len = k1 + k2 + k3;
  1400. cv::hal::exp(W, W, len); //邻域内所有采样点落在子区域的像素的高斯权值
  1401. cv::hal::fastAtan2(Y, X, Angle, len, true); //邻域内所有采样点落在子区域的像素的梯度方向,角度范围是0-360度
  1402. cv::hal::magnitude(X, Y, Mag, len); //邻域内所有采样点落在子区域的像素的梯度幅度
  1403. //计算每个特征点的特征描述子
  1404. for (int k = 0; k < len; ++k)
  1405. {
  1406. float rbin = RBin[k], cbin = CBin[k]; //子区域内像素点坐标,rbin,cbin范围是(-1,d)
  1407. //离特征点进的邻域
  1408. if (k < k1)
  1409. {
  1410. //子区域内像素点处理后的方向
  1411. float obin = (Angle[k] - main_angle) * bin_per_rad_1;
  1412. float mag = Mag[k] * W[k]; //子区域内像素点乘以权值后的梯度幅值
  1413. int r0 = cvFloor(rbin); //ro取值集合是{-1,0,1,2,3},向下取整
  1414. int c0 = cvFloor(cbin); //c0取值集合是{-1,0,1,2,3}
  1415. int o0 = cvFloor(obin);
  1416. rbin = rbin - r0; //子区域内像素点坐标的小数部分,用于线性插值
  1417. cbin = cbin - c0;
  1418. obin = obin - o0;
  1419. //限制范围为梯度直方图横坐标[0,n)
  1420. if (o0 < 0)
  1421. o0 = o0 + n1;
  1422. if (o0 >= n1)
  1423. o0 = o0 - n1;
  1424. //三线性插值用于计算落在两个子区域之间的像素对两个子区域的作用,并把其分配到对应子区域的8个方向上
  1425. //使用三线性插值(即三维)方法,计算直方图
  1426. float v_r1 = mag * rbin; //第二行分配的值
  1427. float v_r0 = mag - v_r1; //第一行分配的值
  1428. float v_rc11 = v_r1 * cbin; //第二行第二列分配的值
  1429. float v_rc10 = v_r1 - v_rc11; //第二行第一列分配的值
  1430. float v_rc01 = v_r0 * cbin; //第一行第二列分配的值
  1431. float v_rc00 = v_r0 - v_rc01;
  1432. float v_rco111 = v_rc11 * obin; //第二行第二列第二个方向上分配的值,每个采样点去邻近两个方向
  1433. float v_rco110 = v_rc11 - v_rco111; //第二行第二列第一个方向上分配的值
  1434. float v_rco101 = v_rc10 * obin;
  1435. float v_rco100 = v_rc10 - v_rco101;
  1436. float v_rco011 = v_rc01 * obin;
  1437. float v_rco010 = v_rc01 - v_rco011;
  1438. float v_rco001 = v_rc00 * obin;
  1439. float v_rco000 = v_rc00 - v_rco001;
  1440. //该像素所在网格的索引
  1441. int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n1 + 2) + o0;
  1442. hist[idx] += v_rco000;
  1443. hist[idx + 1] += v_rco001;
  1444. hist[idx + n1 + 2] += v_rco010;
  1445. hist[idx + n1 + 3] += v_rco011;
  1446. hist[idx + (d + 2) * (n1 + 2)] += v_rco100;
  1447. hist[idx + (d + 2) * (n1 + 2) + 1] += v_rco101;
  1448. hist[idx + (d + 3) * (n1 + 2)] += v_rco110;
  1449. hist[idx + (d + 3) * (n1 + 2) + 1] += v_rco111;
  1450. }
  1451. //离特征点远的邻域
  1452. else if (k >= k1 && k < k2)
  1453. {
  1454. //子区域内像素点处理后的方向
  1455. float obin = (Angle[k] - main_angle) * bin_per_rad_2;
  1456. float mag = Mag[k] * W[k]; //子区域内像素点乘以权值后的梯度幅值
  1457. int r0 = cvFloor(rbin); //ro取值集合是{-1,0,1,2,3},向下取整
  1458. int c0 = cvFloor(cbin); //c0取值集合是{-1,0,1,2,3}
  1459. int o0 = cvFloor(obin);
  1460. rbin = rbin - r0; //子区域内像素点坐标的小数部分,用于线性插值
  1461. cbin = cbin - c0;
  1462. obin = obin - o0;
  1463. //限制范围为梯度直方图横坐标[0,n)
  1464. if (o0 < 0)
  1465. o0 = o0 + n2;
  1466. if (o0 >= n1)
  1467. o0 = o0 - n2;
  1468. //三线性插值用于计算落在两个子区域之间的像素对两个子区域的作用,并把其分配到对应子区域的8个方向上
  1469. //使用三线性插值(即三维)方法,计算直方图
  1470. float v_r1 = mag * rbin; //第二行分配的值
  1471. float v_r0 = mag - v_r1; //第一行分配的值
  1472. float v_rc11 = v_r1 * cbin; //第二行第二列分配的值
  1473. float v_rc10 = v_r1 - v_rc11; //第二行第一列分配的值
  1474. float v_rc01 = v_r0 * cbin; //第一行第二列分配的值
  1475. float v_rc00 = v_r0 - v_rc01;
  1476. float v_rco111 = v_rc11 * obin; //第二行第二列第二个方向上分配的值,每个采样点去邻近两个方向
  1477. float v_rco110 = v_rc11 - v_rco111; //第二行第二列第一个方向上分配的值
  1478. float v_rco101 = v_rc10 * obin;
  1479. float v_rco100 = v_rc10 - v_rco101;
  1480. float v_rco011 = v_rc01 * obin;
  1481. float v_rco010 = v_rc01 - v_rco011;
  1482. float v_rco001 = v_rc00 * obin;
  1483. float v_rco000 = v_rc00 - v_rco001;
  1484. //该像素所在网格的索引
  1485. int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n2 + 2) + o0;
  1486. hist[idx] += v_rco000;
  1487. hist[idx + 1] += v_rco001;
  1488. hist[idx + n2 + 2] += v_rco010;
  1489. hist[idx + n2 + 3] += v_rco011;
  1490. hist[idx + (d + 2) * (n2 + 2)] += v_rco100;
  1491. hist[idx + (d + 2) * (n2 + 2) + 1] += v_rco101;
  1492. hist[idx + (d + 3) * (n2 + 2)] += v_rco110;
  1493. hist[idx + (d + 3) * (n2 + 2) + 1] += v_rco111;
  1494. }
  1495. else
  1496. {
  1497. //子区域内像素点处理后的方向
  1498. float obin = (Angle[k] - main_angle) * bin_per_rad_3;
  1499. float mag = Mag[k] * W[k]; //子区域内像素点乘以权值后的梯度幅值
  1500. int r0 = cvFloor(rbin); //ro取值集合是{-1,0,1,2,3},向下取整
  1501. int c0 = cvFloor(cbin); //c0取值集合是{-1,0,1,2,3}
  1502. int o0 = cvFloor(obin);
  1503. rbin = rbin - r0; //子区域内像素点坐标的小数部分,用于线性插值
  1504. cbin = cbin - c0;
  1505. obin = obin - o0;
  1506. //限制范围为梯度直方图横坐标[0,n)
  1507. if (o0 < 0)
  1508. o0 = o0 + n3;
  1509. if (o0 >= n1)
  1510. o0 = o0 - n3;
  1511. //三线性插值用于计算落在两个子区域之间的像素对两个子区域的作用,并把其分配到对应子区域的8个方向上
  1512. //使用三线性插值(即三维)方法,计算直方图
  1513. float v_r1 = mag * rbin; //第二行分配的值
  1514. float v_r0 = mag - v_r1; //第一行分配的值
  1515. float v_rc11 = v_r1 * cbin; //第二行第二列分配的值
  1516. float v_rc10 = v_r1 - v_rc11; //第二行第一列分配的值
  1517. float v_rc01 = v_r0 * cbin; //第一行第二列分配的值
  1518. float v_rc00 = v_r0 - v_rc01;
  1519. float v_rco111 = v_rc11 * obin; //第二行第二列第二个方向上分配的值,每个采样点去邻近两个方向
  1520. float v_rco110 = v_rc11 - v_rco111; //第二行第二列第一个方向上分配的值
  1521. float v_rco101 = v_rc10 * obin;
  1522. float v_rco100 = v_rc10 - v_rco101;
  1523. float v_rco011 = v_rc01 * obin;
  1524. float v_rco010 = v_rc01 - v_rco011;
  1525. float v_rco001 = v_rc00 * obin;
  1526. float v_rco000 = v_rc00 - v_rco001;
  1527. //该像素所在网格的索引
  1528. int idx = ((r0 + 1) * (d + 2) + c0 + 1) * (n3 + 2) + o0;
  1529. hist[idx] += v_rco000;
  1530. hist[idx + 1] += v_rco001;
  1531. hist[idx + n3 + 2] += v_rco010;
  1532. hist[idx + n3 + 3] += v_rco011;
  1533. hist[idx + (d + 2) * (n3 + 2)] += v_rco100;
  1534. hist[idx + (d + 2) * (n3 + 2) + 1] += v_rco101;
  1535. hist[idx + (d + 3) * (n3 + 2)] += v_rco110;
  1536. hist[idx + (d + 3) * (n3 + 2) + 1] += v_rco111;
  1537. }
  1538. }
  1539. //由于圆周循环的特性,对计算以后幅角小于 0 度或大于 360 度的值重新进行调整,使
  1540. //其在 0~360 度之间
  1541. for (int i = 0; i < d; ++i)
  1542. {
  1543. for (int j = 0; j < d; ++j)
  1544. {
  1545. int idx = ((i + 1) * (d + 2) + (j + 1)) * (n + 2);
  1546. hist[idx] += hist[idx + n];
  1547. //hist[idx + 1] += hist[idx + n + 1];//opencv源码中这句话是多余的,hist[idx + n + 1]永远是0.0
  1548. for (int k = 0; k < n; ++k)
  1549. descriptor[(i * d + j) * n + k] = hist[idx + k];
  1550. }
  1551. }
  1552. //对描述子进行归一化
  1553. int lenght = d * d * n;
  1554. float norm = 0;
  1555. //计算特征描述向量的模值的平方
  1556. for (int i = 0; i < lenght; ++i)
  1557. {
  1558. norm = norm + descriptor[i] * descriptor[i];
  1559. }
  1560. norm = sqrt(norm); //特征描述向量的模值
  1561. //此次归一化能去除光照的影响
  1562. for (int i = 0; i < lenght; ++i)
  1563. {
  1564. descriptor[i] = descriptor[i] / norm;
  1565. }
  1566. //阈值截断,去除特征描述向量中大于 0.2 的值,能消除非线性光照的影响(相机饱和度对某些放的梯度影响较大,对方向的影响较小)
  1567. for (int i = 0; i < lenght; ++i)
  1568. {
  1569. descriptor[i] = min(descriptor[i], DESCR_MAG_THR);
  1570. }
  1571. //再次归一化,能够提高特征的独特性
  1572. norm = 0;
  1573. for (int i = 0; i < lenght; ++i)
  1574. {
  1575. norm = norm + descriptor[i] * descriptor[i];
  1576. }
  1577. norm = sqrt(norm);
  1578. for (int i = 0; i < lenght; ++i)
  1579. {
  1580. descriptor[i] = descriptor[i] / norm;
  1581. }
  1582. }
  1583. /********************************该函数计算所有特征点特征描述子***************************/
  1584. /*gauss_pyr表示高斯金字塔
  1585. keypoints表示特征点、
  1586. descriptors表示生成的特征点的描述子*/
  1587. void mySift::calc_sift_descriptors(const vector<vector<Mat>>& gauss_pyr, vector<KeyPoint>& keypoints,
  1588. Mat& descriptors, const vector<Mat>& amplit, const vector<Mat>& orient)
  1589. {
  1590. int d = DESCR_WIDTH; //d=4,特征点邻域网格个数是d x d
  1591. int n = DESCR_HIST_BINS; //n=8,每个网格特征点梯度角度等分为8个方向
  1592. descriptors.create(keypoints.size(), d * d * n, CV_32FC1); //分配空间
  1593. for (size_t i = 0; i < keypoints.size(); ++i) //对于每一个特征点
  1594. {
  1595. int octaves, layer;
  1596. //得到特征点所在的组号,层号
  1597. octaves = keypoints[i].octave & 255;
  1598. layer = (keypoints[i].octave >> 8) & 255;
  1599. //得到特征点相对于本组的坐标,不是最底层
  1600. Point2f pt(keypoints[i].pt.x / (1 << octaves), keypoints[i].pt.y / (1 << octaves));
  1601. float scale = keypoints[i].size / (1 << octaves); //得到特征点相对于本组的尺度
  1602. float main_angle = keypoints[i].angle; //特征点主方向
  1603. //计算该点的描述子
  1604. calc_sift_descriptor(gauss_pyr[octaves][layer], main_angle, pt, scale, d, n, descriptors.ptr<float>((int)i));
  1605. //improve_calc_sift_descriptor(gauss_pyr[octaves][layer], main_angle, pt, scale, d, n, descriptors.ptr<float>((int)i));
  1606. //calc_gloh_descriptor(amplit[octaves], orient[octaves], pt, scale, main_angle, d, n, descriptors.ptr<float>((int)i));
  1607. if (double_size)//如果图像尺寸扩大一倍
  1608. {
  1609. keypoints[i].pt.x = keypoints[i].pt.x / 2.f;
  1610. keypoints[i].pt.y = keypoints[i].pt.y / 2.f;
  1611. }
  1612. }
  1613. }
  1614. /*************该函数构建SAR_SIFT尺度空间*****************/
  1615. /*image表示输入的原始图像
  1616. sar_harris_fun表示尺度空间的Sar_harris函数
  1617. amplit表示尺度空间像素的梯度幅度
  1618. orient表示尺度空间像素的梯度方向
  1619. */
  1620. void mySift::build_sar_sift_space(const Mat& image, vector<Mat>& sar_harris_fun, vector<Mat>& amplit, vector<Mat>& orient)
  1621. {
  1622. //转换输入图像格式
  1623. Mat gray_image;
  1624. if (image.channels() != 1)
  1625. cvtColor(image, gray_image, CV_RGB2GRAY);
  1626. else
  1627. gray_image = image;
  1628. //把图像转换为0-1之间的浮点数据
  1629. Mat float_image;
  1630. double ratio = pow(2, 1.0 / 3.0); //相邻两层的尺度比,默认是2^(1/3)
  1631. //在这里转换为0-1之间的浮点数据和转换为0-255之间的浮点数据,效果是一样的
  1632. //gray_image.convertTo(float_image, CV_32FC1, 1.f / 255.f, 0.f);//转换为0-1之间
  1633. gray_image.convertTo(float_image, CV_32FC1, 1, 0.f); //转换为0-255之间的浮点数
  1634. //分配内存
  1635. sar_harris_fun.resize(Mmax);
  1636. amplit.resize(Mmax);
  1637. orient.resize(Mmax);
  1638. for (int i = 0; i < Mmax; ++i)
  1639. {
  1640. float scale = (float)sigma * (float)pow(ratio, i); //获得当前层的尺度
  1641. int radius = cvRound(2 * scale);
  1642. Mat kernel;
  1643. roewa_kernel(radius, scale, kernel);
  1644. //四个滤波模板生成
  1645. Mat W34 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1);
  1646. Mat W12 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1);
  1647. Mat W14 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1);
  1648. Mat W23 = Mat::zeros(2 * radius + 1, 2 * radius + 1, CV_32FC1);
  1649. kernel(Range(radius + 1, 2 * radius + 1), Range::all()).copyTo(W34(Range(radius + 1, 2 * radius + 1), Range::all()));
  1650. kernel(Range(0, radius), Range::all()).copyTo(W12(Range(0, radius), Range::all()));
  1651. kernel(Range::all(), Range(radius + 1, 2 * radius + 1)).copyTo(W14(Range::all(), Range(radius + 1, 2 * radius + 1)));
  1652. kernel(Range::all(), Range(0, radius)).copyTo(W23(Range::all(), Range(0, radius)));
  1653. //滤波
  1654. Mat M34, M12, M14, M23;
  1655. double eps = 0.00001;
  1656. filter2D(float_image, M34, CV_32FC1, W34, Point(-1, -1), eps);
  1657. filter2D(float_image, M12, CV_32FC1, W12, Point(-1, -1), eps);
  1658. filter2D(float_image, M14, CV_32FC1, W14, Point(-1, -1), eps);
  1659. filter2D(float_image, M23, CV_32FC1, W23, Point(-1, -1), eps);
  1660. //计算水平梯度和竖直梯度
  1661. Mat Gx, Gy;
  1662. log((M14) / (M23), Gx);
  1663. log((M34) / (M12), Gy);
  1664. //计算梯度幅度和梯度方向
  1665. magnitude(Gx, Gy, amplit[i]);
  1666. phase(Gx, Gy, orient[i], true);
  1667. //构建sar-Harris矩阵
  1668. //Mat Csh_11 = log(scale)*log(scale)*Gx.mul(Gx);
  1669. //Mat Csh_12 = log(scale)*log(scale)*Gx.mul(Gy);
  1670. //Mat Csh_22 = log(scale)*log(scale)*Gy.mul(Gy);
  1671. Mat Csh_11 = scale * scale * Gx.mul(Gx);
  1672. Mat Csh_12 = scale * scale * Gx.mul(Gy);
  1673. Mat Csh_22 = scale * scale * Gy.mul(Gy);//此时阈值为0.8
  1674. //Mat Csh_11 = Gx.mul(Gx);
  1675. //Mat Csh_12 = Gx.mul(Gy);
  1676. //Mat Csh_22 = Gy.mul(Gy);//此时阈值为0.8/100
  1677. //高斯权重
  1678. float gauss_sigma = sqrt(2.f) * scale;
  1679. int size = cvRound(3 * gauss_sigma);
  1680. Size kern_size(2 * size + 1, 2 * size + 1);
  1681. GaussianBlur(Csh_11, Csh_11, kern_size, gauss_sigma, gauss_sigma);
  1682. GaussianBlur(Csh_12, Csh_12, kern_size, gauss_sigma, gauss_sigma);
  1683. GaussianBlur(Csh_22, Csh_22, kern_size, gauss_sigma, gauss_sigma);
  1684. /*Mat gauss_kernel;//自定义圆形高斯核
  1685. gauss_circle(size, gauss_sigma, gauss_kernel);
  1686. filter2D(Csh_11, Csh_11, CV_32FC1, gauss_kernel);
  1687. filter2D(Csh_12, Csh_12, CV_32FC1, gauss_kernel);
  1688. filter2D(Csh_22, Csh_22, CV_32FC1, gauss_kernel);*/
  1689. Mat Csh_21 = Csh_12;
  1690. //构建sar_harris函数
  1691. Mat temp_add = Csh_11 + Csh_22;
  1692. double d = 0.04; //sar_haiirs函数表达式中的任意参数,默认是0.04
  1693. sar_harris_fun[i] = Csh_11.mul(Csh_22) - Csh_21.mul(Csh_12) - (float)d * temp_add.mul(temp_add);
  1694. }
  1695. }
  1696. /***************该函数计算所有特征点的特征向量*************/
  1697. /*amplit表示尺度空间像素幅度
  1698. orient表示尺度空间像素梯度角度
  1699. keys表示检测到的特征点
  1700. descriptors表示特征点描述子向量,【M x N】,M表示描述子个数,N表示描述子维度
  1701. */
  1702. void mySift::calc_gloh_descriptors(const vector<Mat>& amplit, const vector<Mat>& orient, const vector<KeyPoint>& keys, Mat& descriptors)
  1703. {
  1704. int d = SAR_SIFT_GLOH_ANG_GRID; //d=4或者d=8
  1705. int n = SAR_SIFT_DES_ANG_BINS; //n=8默认
  1706. int num_keys = (int)keys.size();
  1707. int grids = 2 * d + 1;
  1708. //descriptors.create(num_keys, grids * n, CV_32FC1);
  1709. descriptors.create(num_keys, grids * n, CV_32FC1);
  1710. for (int i = 0; i < num_keys; ++i)
  1711. {
  1712. int octaves = keys[i].octave & 255; //特征点所在层
  1713. float* ptr_des = descriptors.ptr<float>(i);
  1714. float scale = keys[i].size / (1 << octaves); //得到特征点相对于本组的尺度; //特征点所在层的尺度
  1715. float main_ori = keys[i].angle; //特征点主方向
  1716. //得到特征点相对于本组的坐标,不是最底层
  1717. Point2f point(keys[i].pt.x / (1 << octaves), keys[i].pt.y / (1 << octaves));
  1718. cout << "layer=" << octaves << endl;
  1719. cout << "scale=" << scale << endl;
  1720. //计算该特征点的特征描述子
  1721. calc_gloh_descriptor(amplit[octaves], orient[octaves], point, scale, main_ori, d, n, ptr_des);
  1722. }
  1723. }
  1724. //特征点检测和特征点描述把整个 SIFT 算子都涵盖在内了//
  1725. /******************************特征点检测*********************************/
  1726. /*image表示输入的图像
  1727. gauss_pyr表示生成的高斯金字塔
  1728. dog_pyr表示生成的高斯差分DOG金字塔
  1729. keypoints表示检测到的特征点
  1730. vector<float>& cell_contrast 用于存放一个单元格中所有特征点的对比度
  1731. vector<float>& cell_contrasts用于存放一个尺度层中所有单元格中特征点的对比度
  1732. vector<vector<vector<float>>>& all_cell_contrasts用于存放所有尺度层中所有单元格的对比度
  1733. vector<vector<float>>& average_contrast用于存放所有尺度层中多有单元格的平均对比度*/
  1734. void mySift::detect(const Mat& image, vector<vector<Mat>>& gauss_pyr, vector<vector<Mat>>& dog_pyr, vector<KeyPoint>& keypoints,
  1735. vector<vector<vector<float>>>& all_cell_contrasts,
  1736. vector<vector<float>>& average_contrast, vector<vector<int>>& n_cells, vector<int>& num_cell, vector<vector<int>>& available_n,
  1737. vector<int>& available_num, vector<KeyPoint>& final_keypoints,
  1738. vector<KeyPoint>& Final_keypoints, vector<KeyPoint>& Final_Keypoints)
  1739. {
  1740. if (image.empty() || image.depth() != CV_8U)
  1741. CV_Error(CV_StsBadArg, "输入图像为空,或者图像深度不是CV_8U");
  1742. //计算高斯金字塔组数
  1743. int nOctaves;
  1744. nOctaves = num_octaves(image);
  1745. //生成高斯金字塔第一层图像
  1746. Mat init_gauss;
  1747. create_initial_image(image, init_gauss);
  1748. //生成高斯尺度空间图像
  1749. build_gaussian_pyramid(init_gauss, gauss_pyr, nOctaves);
  1750. //生成高斯差分金字塔(DOG金字塔,or LOG金字塔)
  1751. build_dog_pyramid(dog_pyr, gauss_pyr);
  1752. //在DOG金字塔上检测特征点
  1753. find_scale_space_extrema1(dog_pyr, gauss_pyr, keypoints); //原始 SIFT 算子
  1754. // UR_SIFT,仅仅是检测特征点,并未对不理想的点进行筛选
  1755. /*UR_SIFT_find_scale_space_extrema(dog_pyr, gauss_pyr, keypoints, all_cell_contrasts,
  1756. average_contrast, n_cells, num_cell, available_n, available_num, final_keypoints, Final_keypoints, Final_Keypoints, N);*/
  1757. //如果指定了特征点个数,并且设定的设置小于默认检测的特征点个数
  1758. if (nfeatures != 0 && nfeatures < (int)keypoints.size())
  1759. {
  1760. //特征点响应值(即对比度,对比度越小越不稳定)从大到小排序
  1761. sort(keypoints.begin(), keypoints.end(), [](const KeyPoint& a, const KeyPoint& b) {return a.response > b.response; });
  1762. //删除点多余的特征点
  1763. keypoints.erase(keypoints.begin() + nfeatures, keypoints.end());
  1764. }
  1765. }
  1766. /**********************特征点描述*******************/
  1767. /*gauss_pyr表示高斯金字塔
  1768. keypoints表示特征点集合
  1769. descriptors表示特征点的描述子*/
  1770. void mySift::comput_des(const vector<vector<Mat>>& gauss_pyr, vector<KeyPoint>& final_keypoints, const vector<Mat>& amplit,
  1771. const vector<Mat>& orient, Mat& descriptors)
  1772. {
  1773. calc_sift_descriptors(gauss_pyr, final_keypoints, descriptors, amplit, orient);
  1774. }

3、 myMatch.h

  1. #pragma once
  2. #include<opencv2\core\core.hpp>
  3. #include<opencv2\features2d\features2d.hpp>
  4. #include<vector>
  5. #include<string>
  6. #include<iostream>
  7. const double dis_ratio1 = 0.75; //最近邻和次近邻距离比阈值,就目前测试来看 dis_ratio = 0.75 时正确匹配的数量相对较多
  8. const double dis_ratio2 = 0.8;
  9. const double dis_ratio3 = 0.9;
  10. const float ransac_error = 1.5; //ransac算法误差阈值
  11. const double FSC_ratio_low = 0.8;
  12. const double FSC_ratio_up = 1;
  13. const int pointsCount = 9; // k均值聚类数据点个数
  14. const int clusterCount = 3; // k均值聚类质心的个数
  15. enum DIS_CRIT { Euclidean = 0, COS }; //距离度量准则
  16. using namespace std;
  17. using namespace cv;
  18. class myMatch
  19. {
  20. public:
  21. myMatch();
  22. ~myMatch();
  23. //该函数根据正确的匹配点对,计算出图像之间的变换关系
  24. Mat LMS(const Mat& match1_xy, const Mat& match2_xy, string model, float& rmse);
  25. //改进版LMS超定方程
  26. Mat improve_LMS(const Mat& match1_xy, const Mat& match2_xy, string model, float& rmse);
  27. //该函数删除错误的匹配点对
  28. Mat ransac(const vector<Point2f>& points_1, const vector<Point2f>& points_2, string model, float threshold, vector<bool>& inliers, float& rmse);
  29. //绘制棋盘图像
  30. void mosaic_map(const Mat& image_1, const Mat& image_2, Mat& chessboard_1, Mat& chessboard_2, Mat& mosaic_image, int width);
  31. //该函数把两幅配准后的图像进行融合镶嵌
  32. void image_fusion(const Mat& image_1, const Mat& image_2, const Mat T, Mat& fusion_image, Mat& matched_image);
  33. //该函数进行描述子的最近邻和次近邻匹配
  34. void match_des(const Mat& des_1, const Mat& des_2, vector<vector<DMatch>>& dmatchs, DIS_CRIT dis_crite);
  35. //建立尺度直方图、ROM 直方图
  36. void scale_ROM_Histogram(const vector<DMatch>& matches, float* scale_hist, float* ROM_hist, int n);
  37. //该函数删除错误匹配点对,并进行配准
  38. Mat match(const Mat& image_1, const Mat& image_2, const vector<vector<DMatch>>& dmatchs, vector<KeyPoint> keys_1,
  39. vector<KeyPoint> keys_2, string model, vector<DMatch>& right_matchs, Mat& matched_line, vector<DMatch>& init_matchs);
  40. };

4、 myMatch.cpp

  1. #include"myMatch.h"
  2. #include<opencv2\imgproc\types_c.h>
  3. #include<opencv2\imgproc\imgproc.hpp>
  4. #include<opencv2\highgui\highgui.hpp>
  5. #include<opencv2\features2d\features2d.hpp> //特征提取
  6. #include<algorithm>
  7. #include<vector>
  8. #include<cmath>
  9. #include<opencv.hpp>
  10. #include <numeric> //用于容器元素求和
  11. using namespace std;
  12. using namespace cv;
  13. //using namespace gpu;
  14. RNG rng(100);
  15. myMatch::myMatch()
  16. {
  17. }
  18. /********该函数根据正确的匹配点对,计算出图像之间的变换关系********/
  19. /*注意:输入几个点都能计算对应的 x 矩阵,(2N,8)*(8,1)=(2N,1)
  20. match1_xy表示参考图像特征点坐标集合,[M x 2]矩阵,M表示特征的个数
  21. match2_xy表示待配准图像特征点集合,[M x 2]矩阵,M表示特征点集合
  22. model表示变换类型,“相似变换”,"仿射变换","透视变换"
  23. rmse表示均方根误差
  24. 返回值为计算得到的3 x 3矩阵参数
  25. */
  26. Mat myMatch::LMS(const Mat& match1_xy, const Mat& match2_xy, string model, float& rmse)
  27. {
  28. if (match1_xy.rows != match2_xy.rows)
  29. CV_Error(CV_StsBadArg, "LMS模块输入特征点对个数不一致!");
  30. if (!(model == string("affine") || model == string("similarity") ||
  31. model == string("perspective") || model == string("projective")))
  32. CV_Error(CV_StsBadArg, "LMS模块图像变换类型输入错误!");
  33. const int N = match1_xy.rows; //特征点个数
  34. Mat match2_xy_trans, match1_xy_trans; //特征点坐标转置
  35. transpose(match1_xy, match1_xy_trans); //矩阵转置(2,M)
  36. transpose(match2_xy, match2_xy_trans);
  37. Mat change = Mat::zeros(3, 3, CV_32FC1); //变换矩阵
  38. //A*X=B,接下来部分仿射变换和透视变换一样,如果特征点个数是M,则A=[2*M,6]矩阵
  39. //A=[x1,y1,0,0,1,0;0,0,x1,y1,0,1;.....xn,yn,0,0,1,0;0,0,xn,yn,0,1],应该是改版过的
  40. Mat A = Mat::zeros(2 * N, 6, CV_32FC1);
  41. for (int i = 0; i < N; ++i)
  42. {
  43. A.at<float>(2 * i, 0) = match2_xy.at<float>(i, 0);//x
  44. A.at<float>(2 * i, 1) = match2_xy.at<float>(i, 1);//y
  45. A.at<float>(2 * i, 4) = 1.f;
  46. A.at<float>(2 * i + 1, 2) = match2_xy.at<float>(i, 0);
  47. A.at<float>(2 * i + 1, 3) = match2_xy.at<float>(i, 1);
  48. A.at<float>(2 * i + 1, 5) = 1.f;
  49. }
  50. //如果特征点个数是M,那个B=[2*M,1]矩阵
  51. //B=[u1,v1,u2,v2,.....,un,vn]
  52. Mat B;
  53. B.create(2 * N, 1, CV_32FC1);
  54. for (int i = 0; i < N; ++i)
  55. {
  56. B.at<float>(2 * i, 0) = match1_xy.at<float>(i, 0); //x
  57. B.at<float>(2 * i + 1, 0) = match1_xy.at<float>(i, 1);//y
  58. }
  59. //如果是仿射变换
  60. if (model == string("affine"))
  61. {
  62. Vec6f values;
  63. solve(A, B, values, DECOMP_QR);
  64. change = (Mat_<float>(3, 3) << values(0), values(1), values(4),
  65. values(2), values(3), values(5),
  66. +0.0f, +0.0f, 1.0f);
  67. Mat temp_1 = change(Range(0, 2), Range(0, 2)); //尺度和旋转量
  68. Mat temp_2 = change(Range(0, 2), Range(2, 3)); //平移量
  69. Mat match2_xy_change = temp_1 * match2_xy_trans + repeat(temp_2, 1, N);
  70. Mat diff = match2_xy_change - match1_xy_trans; //求差
  71. pow(diff, 2.f, diff);
  72. rmse = (float)sqrt(sum(diff)(0) * 1.0) / N; //sum输出是各个通道的和, / N 初始实在括号里面
  73. }
  74. //如果是透视变换
  75. else if (model == string("perspective"))
  76. {
  77. /*透视变换模型
  78. [u'*w,v'*w, w]'=[u,v,w]' = [a1, a2, a5;
  79. a3, a4, a6;
  80. a7, a8, 1] * [x, y, 1]'
  81. [u',v']'=[x,y,0,0,1,0,-u'x, -u'y;
  82. 0, 0, x, y, 0, 1, -v'x,-v'y] * [a1, a2, a3, a4, a5, a6, a7, a8]'
  83. 即,Y = A*X */
  84. //构造 A 矩阵的后两列
  85. Mat A2;
  86. A2.create(2 * N, 2, CV_32FC1);
  87. for (int i = 0; i < N; ++i)
  88. {
  89. A2.at<float>(2 * i, 0) = match1_xy.at<float>(i, 0) * match2_xy.at<float>(i, 0) * (-1.f);
  90. A2.at<float>(2 * i, 1) = match1_xy.at<float>(i, 0) * match2_xy.at<float>(i, 1) * (-1.f);
  91. A2.at<float>(2 * i + 1, 0) = match1_xy.at<float>(i, 1) * match2_xy.at<float>(i, 0) * (-1.f);
  92. A2.at<float>(2 * i + 1, 1) = match1_xy.at<float>(i, 1) * match2_xy.at<float>(i, 1) * (-1.f);
  93. }
  94. Mat A1; //完成的 A 矩阵,(8,8)
  95. A1.create(2 * N, 8, CV_32FC1);
  96. A.copyTo(A1(Range::all(), Range(0, 6)));
  97. A2.copyTo(A1(Range::all(), Range(6, 8)));
  98. Mat values; //values中存放的是待求的8个参数
  99. solve(A1, B, values, DECOMP_QR); //(2N,8)*(8,1)=(2N,1)好像本身就有点超定矩阵的意思
  100. change.at<float>(0, 0) = values.at<float>(0);
  101. change.at<float>(0, 1) = values.at<float>(1);
  102. change.at<float>(0, 2) = values.at<float>(4);
  103. change.at<float>(1, 0) = values.at<float>(2);
  104. change.at<float>(1, 1) = values.at<float>(3);
  105. change.at<float>(1, 2) = values.at<float>(5);
  106. change.at<float>(2, 0) = values.at<float>(6);
  107. change.at<float>(2, 1) = values.at<float>(7);
  108. change.at<float>(2, 2) = 1.f;
  109. Mat temp1 = Mat::ones(1, N, CV_32FC1);
  110. Mat temp2;
  111. temp2.create(3, N, CV_32FC1);
  112. match2_xy_trans.copyTo(temp2(Range(0, 2), Range::all()));
  113. temp1.copyTo(temp2(Range(2, 3), Range::all()));
  114. Mat match2_xy_change = change * temp2; //待配准图像中的特征点在参考图中的映射结果
  115. Mat match2_xy_change_12 = match2_xy_change(Range(0, 2), Range::all());
  116. //float* temp_ptr = match2_xy_change.ptr<float>(2);
  117. float* temp_ptr = match2_xy_change.ptr<float>(2);
  118. for (int i = 0; i < N; ++i)
  119. {
  120. float div_temp = temp_ptr[i];
  121. match2_xy_change_12.at<float>(0, i) = match2_xy_change_12.at<float>(0, i) / div_temp;
  122. match2_xy_change_12.at<float>(1, i) = match2_xy_change_12.at<float>(1, i) / div_temp;
  123. }
  124. Mat diff = match2_xy_change_12 - match1_xy_trans;
  125. pow(diff, 2, diff);
  126. rmse = (float)sqrt(sum(diff)(0) * 1.0) / N; //sum输出是各个通道的和,rmse为输入点的均方误差
  127. }
  128. //如果是相似变换
  129. else if (model == string("similarity"))
  130. {
  131. /*[x, y, 1, 0;
  132. y, -x, 0, 1] * [a, b, c, d]'=[u,v]*/
  133. Mat A3;
  134. A3.create(2 * N, 4, CV_32FC1);
  135. for (int i = 0; i < N; ++i)
  136. {
  137. A3.at<float>(2 * i, 0) = match2_xy.at<float>(i, 0);
  138. A3.at<float>(2 * i, 1) = match2_xy.at<float>(i, 1);
  139. A3.at<float>(2 * i, 2) = 1.f;
  140. A3.at<float>(2 * i, 3) = 0.f;
  141. A3.at<float>(2 * i + 1, 0) = match2_xy.at<float>(i, 1);
  142. A3.at<float>(2 * i + 1, 1) = match2_xy.at<float>(i, 0) * (-1.f);
  143. A3.at<float>(2 * i + 1, 2) = 0.f;
  144. A3.at<float>(2 * i + 1, 3) = 1.f;
  145. }
  146. Vec4f values;
  147. solve(A3, B, values, DECOMP_QR);
  148. change = (Mat_<float>(3, 3) << values(0), values(1), values(2),
  149. values(1) * (-1.0f), values(0), values(3),
  150. +0.f, +0.f, 1.f);
  151. Mat temp_1 = change(Range(0, 2), Range(0, 2));//尺度和旋转量
  152. Mat temp_2 = change(Range(0, 2), Range(2, 3));//平移量
  153. Mat match2_xy_change = temp_1 * match2_xy_trans + repeat(temp_2, 1, N);
  154. Mat diff = match2_xy_change - match1_xy_trans;//求差
  155. pow(diff, 2, diff);
  156. rmse = (float)sqrt(sum(diff)(0) * 1.0) / N;//sum输出是各个通道的和
  157. }
  158. return change;
  159. }
  160. /********改进版LMS超定方程********/
  161. Mat myMatch::improve_LMS(const Mat& match1_xy, const Mat& match2_xy, string model, float& rmse)
  162. {
  163. if (match1_xy.rows != match2_xy.rows)
  164. CV_Error(CV_StsBadArg, "LMS模块输入特征点对个数不一致!");
  165. if (!(model == string("affine") || model == string("similarity") ||
  166. model == string("perspective")))
  167. CV_Error(CV_StsBadArg, "LMS模块图像变换类型输入错误!");
  168. const int N = match1_xy.rows; //特征点个数
  169. Mat match2_xy_trans, match1_xy_trans; //特征点坐标转置
  170. transpose(match1_xy, match1_xy_trans); //矩阵转置(2,M)
  171. transpose(match2_xy, match2_xy_trans);
  172. Mat change = Mat::zeros(3, 3, CV_32FC1); //变换矩阵
  173. //A*X=B,接下来部分仿射变换和透视变换一样,如果特征点个数是M,则A=[2*M,6]矩阵
  174. //A=[x1,y1,0,0,1,0;0,0,x1,y1,0,1;.....xn,yn,0,0,1,0;0,0,xn,yn,0,1],应该是改版过的
  175. Mat A = Mat::zeros(2 * N, 6, CV_32FC1);
  176. for (int i = 0; i < N; ++i)
  177. {
  178. A.at<float>(2 * i, 0) = match2_xy.at<float>(i, 0);//x
  179. A.at<float>(2 * i, 1) = match2_xy.at<float>(i, 1);//y
  180. A.at<float>(2 * i, 4) = 1.f;
  181. //A.at<float>(2 * i, 0) = match2_xy.at<float>(i, 0);//x
  182. //A.at<float>(2 * i, 1) = match2_xy.at<float>(i, 1);//y
  183. //A.at<float>(2 * i, 2) = 1.f;
  184. A.at<float>(2 * i + 1, 2) = match2_xy.at<float>(i, 0);
  185. A.at<float>(2 * i + 1, 3) = match2_xy.at<float>(i, 1);
  186. A.at<float>(2 * i + 1, 5) = 1.f;
  187. /*A.at<float>(2 * i + 1, 3) = match2_xy.at<float>(i, 0);
  188. A.at<float>(2 * i + 1, 4) = match2_xy.at<float>(i, 1);
  189. A.at<float>(2 * i + 1, 5) = 1.f;*/
  190. }
  191. //如果特征点个数是M,那个B=[2*M,1]矩阵
  192. //B=[u1,v1,u2,v2,.....,un,vn]
  193. Mat B;
  194. B.create(2 * N, 1, CV_32FC1);
  195. for (int i = 0; i < N; ++i)
  196. {
  197. B.at<float>(2 * i, 0) = match1_xy.at<float>(i, 0); //x
  198. B.at<float>(2 * i + 1, 0) = match1_xy.at<float>(i, 1);//y
  199. }
  200. //如果是仿射变换
  201. if (model == string("affine"))
  202. {
  203. Vec6f values;
  204. solve(A, B, values, DECOMP_QR);
  205. change = (Mat_<float>(3, 3) << values(0), values(1), values(4),
  206. values(2), values(3), values(5),
  207. +0.0f, +0.0f, 1.0f);
  208. Mat temp_1 = change(Range(0, 2), Range(0, 2));//尺度和旋转量
  209. Mat temp_2 = change(Range(0, 2), Range(2, 3));//平移量
  210. Mat match2_xy_change = temp_1 * match2_xy_trans + repeat(temp_2, 1, N);
  211. Mat diff = match2_xy_change - match1_xy_trans;//求差
  212. pow(diff, 2.f, diff);
  213. rmse = (float)sqrt(sum(diff)(0) * 1.0 / N);//sum输出是各个通道的和
  214. }
  215. //如果是透视变换
  216. else if (model == string("perspective"))
  217. {
  218. /*透视变换模型
  219. [u'*w,v'*w, w]'=[u,v,w]' = [a1, a2, a5;
  220. a3, a4, a6;
  221. a7, a8, 1] * [x, y, 1]'
  222. [u',v']'=[x,y,0,0,1,0,-u'x, -u'y;
  223. 0, 0, x, y, 0, 1, -v'x,-v'y] * [a1, a2, a3, a4, a5, a6, a7, a8]'
  224. 即,Y = A*X */
  225. //构造 A 矩阵的后两列
  226. Mat A2;
  227. A2.create(2 * N, 2, CV_32FC1);
  228. for (int i = 0; i < N; ++i)
  229. {
  230. A2.at<float>(2 * i, 0) = match1_xy.at<float>(i, 0) * match2_xy.at<float>(i, 0) * (-1.f);
  231. A2.at<float>(2 * i, 1) = match1_xy.at<float>(i, 0) * match2_xy.at<float>(i, 1) * (-1.f);
  232. A2.at<float>(2 * i + 1, 0) = match1_xy.at<float>(i, 1) * match2_xy.at<float>(i, 0) * (-1.f);
  233. A2.at<float>(2 * i + 1, 1) = match1_xy.at<float>(i, 1) * match2_xy.at<float>(i, 1) * (-1.f);
  234. }
  235. Mat A1; //完整的 A 矩阵,(8,8)
  236. A1.create(2 * N, 8, CV_32FC1);
  237. A.copyTo(A1(Range::all(), Range(0, 6)));
  238. A2.copyTo(A1(Range::all(), Range(6, 8)));
  239. Mat AA1, balance;
  240. Mat evects, evals;
  241. transpose(A1, AA1); //求矩阵 A1 的转置
  242. balance = AA1 * A1;
  243. double a[8][8];
  244. for (int i = 0; i < 8; i++)
  245. {
  246. for (int j = 0; j < 8; j++)
  247. {
  248. a[i][j] = balance.at<float>(i, j);
  249. }
  250. }
  251. //构造输入矩阵
  252. CvMat SrcMatrix = cvMat(8, 8, CV_32FC1, a);
  253. double b[8][8] =
  254. {
  255. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  256. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  257. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  258. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  259. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  260. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  261. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
  262. {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
  263. };
  264. // 构造输出特征向量矩阵,特征向量按行存储,且与特征值相对应
  265. CvMat ProVector = cvMat(8, 8, CV_32FC1, b);
  266. // 构造输出特征值矩阵,特征值按降序配列
  267. double c[8] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
  268. CvMat ProValue = cvMat(8, 1, CV_32FC1, c);
  269. //求特征向量,最后一行特征向量即对应的 H 矩阵的参数
  270. cvEigenVV(&SrcMatrix, &ProVector, &ProValue, 1.0e-6F);
  271. 输出特征向量矩阵
  272. //for (int i = 0; i < 2; i++)
  273. //{
  274. // for (int j = 0; j < 2; j++)
  275. // printf("%f\t", cvmGet(&ProVector, i, j));
  276. // printf("\n");
  277. //}
  278. //把计算得到的最小特征值对应的特征变量赋给 H 矩阵
  279. change.at<float>(0, 0) = cvmGet(&ProVector, 7, 0);
  280. change.at<float>(0, 1) = cvmGet(&ProVector, 7, 1);
  281. change.at<float>(0, 2) = cvmGet(&ProVector, 7, 2);
  282. change.at<float>(1, 0) = cvmGet(&ProVector, 7, 3);
  283. change.at<float>(1, 1) = cvmGet(&ProVector, 7, 4);
  284. change.at<float>(1, 2) = cvmGet(&ProVector, 7, 5);
  285. change.at<float>(2, 0) = cvmGet(&ProVector, 7, 6);
  286. change.at<float>(2, 1) = cvmGet(&ProVector, 7, 7);
  287. change.at<float>(2, 2) = 1.f;
  288. Mat temp1 = Mat::ones(1, N, CV_32FC1);
  289. Mat temp2; //存放处理后的特征点(x,y,1)T
  290. temp2.create(3, N, CV_32FC1);
  291. match2_xy_trans.copyTo(temp2(Range(0, 2), Range::all()));
  292. temp1.copyTo(temp2(Range(2, 3), Range::all()));
  293. Mat match2_xy_change = change * temp2; //待配准图像中的特征点在参考图中的映射结果
  294. Mat match2_xy_change_12 = match2_xy_change(Range(0, 2), Range::all());
  295. //float* temp_ptr = match2_xy_change.ptr<float>(2);
  296. float* temp_ptr = match2_xy_change.ptr<float>(2);
  297. for (int i = 0; i < N; ++i)
  298. {
  299. float div_temp = temp_ptr[i];
  300. match2_xy_change_12.at<float>(0, i) = match2_xy_change_12.at<float>(0, i) / div_temp;
  301. match2_xy_change_12.at<float>(1, i) = match2_xy_change_12.at<float>(1, i) / div_temp;
  302. }
  303. Mat diff = match2_xy_change_12 - match1_xy_trans;
  304. pow(diff, 2, diff);
  305. rmse = (float)sqrt(sum(diff)(0) * 1.0 / N); //sum输出是各个通道的和,rmse为输入点的均方误差
  306. }
  307. //如果是相似变换
  308. else if (model == string("similarity"))
  309. {
  310. /*[x, y, 1, 0;
  311. y, -x, 0, 1] * [a, b, c, d]'=[u,v]*/
  312. Mat A3;
  313. A3.create(2 * N, 4, CV_32FC1);
  314. for (int i = 0; i < N; ++i)
  315. {
  316. A3.at<float>(2 * i, 0) = match2_xy.at<float>(i, 0);
  317. A3.at<float>(2 * i, 1) = match2_xy.at<float>(i, 1);
  318. A3.at<float>(2 * i, 2) = 1.f;
  319. A3.at<float>(2 * i, 3) = 0.f;
  320. A3.at<float>(2 * i + 1, 0) = match2_xy.at<float>(i, 1);
  321. A3.at<float>(2 * i + 1, 1) = match2_xy.at<float>(i, 0) * (-1.f);
  322. A3.at<float>(2 * i + 1, 2) = 0.f;
  323. A3.at<float>(2 * i + 1, 3) = 1.f;
  324. }
  325. Vec4f values;
  326. solve(A3, B, values, DECOMP_QR);
  327. change = (Mat_<float>(3, 3) << values(0), values(1), values(2),
  328. values(1) * (-1.0f), values(0), values(3),
  329. +0.f, +0.f, 1.f);
  330. Mat temp_1 = change(Range(0, 2), Range(0, 2));//尺度和旋转量
  331. Mat temp_2 = change(Range(0, 2), Range(2, 3));//平移量
  332. Mat match2_xy_change = temp_1 * match2_xy_trans + repeat(temp_2, 1, N);
  333. Mat diff = match2_xy_change - match1_xy_trans;//求差
  334. pow(diff, 2, diff);
  335. rmse = (float)sqrt(sum(diff)(0) * 1.0) / N;//sum输出是各个通道的和
  336. }
  337. return change;
  338. }
  339. /*********************该函数删除错误的匹配点对****************************/
  340. /*points_1表示参考图像上匹配的特征点位置
  341. points_2表示待配准图像上匹配的特征点位置
  342. model表示变换模型,“similarity”,"affine",“perspective”
  343. threshold表示内点阈值
  344. inliers表示points_1和points_2中对应的点对是否是正确匹配,如果是,对应元素值为1,否则为0
  345. rmse表示最后所有正确匹配点对计算出来的误差
  346. 返回一个3 x 3矩阵,表示待配准图像到参考图像的变换矩阵
  347. */
  348. Mat myMatch::ransac(const vector<Point2f>& points_1, const vector<Point2f>& points_2, string model, float threshold, vector<bool>& inliers, float& rmse)
  349. {
  350. if (points_1.size() != points_2.size())
  351. CV_Error(CV_StsBadArg, "ransac模块输入特征点数量不一致!");
  352. if (!(model == string("affine") || model == string("similarity") ||
  353. model == string("perspective") || model == string("projective")))
  354. CV_Error(CV_StsBadArg, "ransac模块图像变换类型输入错误!");
  355. const size_t N = points_1.size(); //特征点对数,size_t 类型常用来保存一个数据的大小,通常为整形,可移植性强
  356. int n; //相当于不同模型对应的标签
  357. size_t max_iteration, iterations;
  358. //确定最大迭代次数,就目前来看此法过于简单粗暴,可以使用自适应迭代次数法
  359. if (model == string("similarity"))
  360. {
  361. n = 2;
  362. max_iteration = N * (N - 1) / 2;
  363. }
  364. else if (model == string("affine"))
  365. {
  366. n = 3;
  367. max_iteration = N * (N - 1) * (N - 2) / (2 * 3);
  368. }
  369. else if (model == string("perspective"))
  370. {
  371. n = 4;
  372. max_iteration = N * (N - 1) * (N - 2) / (2 * 3);
  373. }
  374. if (max_iteration > 800)
  375. iterations = 800;
  376. else
  377. iterations = max_iteration;
  378. //取出保存在points_1和points_2中的点坐标,保存在Mat矩阵中,方便处理
  379. Mat arr_1, arr_2; //arr_1,和arr_2是一个[3 x N]的矩阵,每一列表示一个点坐标,第三行全是1
  380. arr_1.create(3, N, CV_32FC1);
  381. arr_2.create(3, N, CV_32FC1);
  382. //获取矩阵每一行的首地址
  383. float* p10 = arr_1.ptr<float>(0), * p11 = arr_1.ptr<float>(1), * p12 = arr_1.ptr<float>(2);
  384. float* p20 = arr_2.ptr<float>(0), * p21 = arr_2.ptr<float>(1), * p22 = arr_2.ptr<float>(2);
  385. //把特征点放到矩阵中
  386. for (size_t i = 0; i < N; ++i)
  387. {
  388. p10[i] = points_1[i].x;
  389. p11[i] = points_1[i].y;
  390. p12[i] = 1.f;
  391. p20[i] = points_2[i].x;
  392. p21[i] = points_2[i].y;
  393. p22[i] = 1.f;
  394. }
  395. Mat rand_mat; //特征点索引
  396. rand_mat.create(1, n, CV_32SC1);
  397. int* p = rand_mat.ptr<int>(0);
  398. Mat sub_arr1, sub_arr2; //存放随机挑选的特征点
  399. sub_arr1.create(n, 2, CV_32FC1);
  400. sub_arr2.create(n, 2, CV_32FC1);
  401. Mat T; //待配准图像到参考图像的变换矩阵
  402. int most_consensus_num = 0; //当前最优一致集个数初始化为0
  403. vector<bool> right;
  404. right.resize(N);
  405. inliers.resize(N);
  406. for (size_t i = 0; i < iterations; ++i) //迭代次数
  407. {
  408. //随机选择n个不同的点对,不同的模型每次随机选择的个数不同
  409. while (1)
  410. {
  411. randu(rand_mat, 0, N - 1); //随机生成n个范围在[0,N-1]之间的数,作为获取特征点的索引
  412. //保证这n个点坐标不相同
  413. if (n == 2 && p[0] != p[1] &&
  414. (p10[p[0]] != p10[p[1]] || p11[p[0]] != p11[p[1]]) &&
  415. (p20[p[0]] != p20[p[1]] || p21[p[0]] != p21[p[1]]))
  416. break;
  417. if (n == 3 && p[0] != p[1] && p[0] != p[2] && p[1] != p[2] &&
  418. (p10[p[0]] != p10[p[1]] || p11[p[0]] != p11[p[1]]) &&
  419. (p10[p[0]] != p10[p[2]] || p11[p[0]] != p11[p[2]]) &&
  420. (p10[p[1]] != p10[p[2]] || p11[p[1]] != p11[p[2]]) &&
  421. (p20[p[0]] != p20[p[1]] || p21[p[0]] != p21[p[1]]) &&
  422. (p20[p[0]] != p20[p[2]] || p21[p[0]] != p21[p[2]]) &&
  423. (p20[p[1]] != p20[p[2]] || p21[p[1]] != p21[p[2]]))
  424. break;
  425. if (n == 4 && p[0] != p[1] && p[0] != p[2] && p[0] != p[3] &&
  426. p[1] != p[2] && p[1] != p[3] && p[2] != p[3] &&
  427. (p10[p[0]] != p10[p[1]] || p11[p[0]] != p11[p[1]]) &&
  428. (p10[p[0]] != p10[p[2]] || p11[p[0]] != p11[p[2]]) &&
  429. (p10[p[0]] != p10[p[3]] || p11[p[0]] != p11[p[3]]) &&
  430. (p10[p[1]] != p10[p[2]] || p11[p[1]] != p11[p[2]]) &&
  431. (p10[p[1]] != p10[p[3]] || p11[p[1]] != p11[p[3]]) &&
  432. (p10[p[2]] != p10[p[3]] || p11[p[2]] != p11[p[3]]) &&
  433. (p20[p[0]] != p20[p[1]] || p21[p[0]] != p21[p[1]]) &&
  434. (p20[p[0]] != p20[p[2]] || p21[p[0]] != p21[p[2]]) &&
  435. (p20[p[0]] != p20[p[3]] || p21[p[0]] != p21[p[3]]) &&
  436. (p20[p[1]] != p20[p[2]] || p21[p[1]] != p21[p[2]]) &&
  437. (p20[p[1]] != p20[p[3]] || p21[p[1]] != p21[p[3]]) &&
  438. (p20[p[2]] != p20[p[3]] || p21[p[2]] != p21[p[3]]))
  439. break;
  440. }
  441. //提取出n个点对
  442. for (int i = 0; i < n; ++i)
  443. {
  444. sub_arr1.at<float>(i, 0) = p10[p[i]];
  445. sub_arr1.at<float>(i, 1) = p11[p[i]];
  446. sub_arr2.at<float>(i, 0) = p20[p[i]];
  447. sub_arr2.at<float>(i, 1) = p21[p[i]];
  448. }
  449. //根据这n个点对,计算初始变换矩阵 T
  450. T = LMS(sub_arr1, sub_arr2, model, rmse);
  451. int consensus_num = 0; //当前一致集(内点)个数
  452. if (model == string("perspective"))
  453. {
  454. //变换矩阵计算待配准图像特征点在参考图像中的映射点
  455. Mat match2_xy_change = T * arr_2; //arr_2 中存放的是待配准图像的特征点 (3,N),
  456. //match2_xy_change(Range(0, 2), Range::all())意思是提取 match2_xy_change 的 0、1 行,所有的列
  457. Mat match2_xy_change_12 = match2_xy_change(Range(0, 2), Range::all());
  458. //获取 match2_xy_change 第二行首地址
  459. float* temp_ptr = match2_xy_change.ptr<float>(2);
  460. for (size_t i = 0; i < N; ++i)
  461. {
  462. float div_temp = temp_ptr[i]; //match2_xy_change 第二行第 i 列值,除以 div_temp ,是为了保证第三行为 1,和原始坐标相对应
  463. match2_xy_change_12.at<float>(0, i) = match2_xy_change_12.at<float>(0, i) / div_temp;
  464. match2_xy_change_12.at<float>(1, i) = match2_xy_change_12.at<float>(1, i) / div_temp;
  465. }
  466. //计算待配准图像特征点在参考图像中的映射点与参考图像中对应点的距离
  467. Mat diff = match2_xy_change_12 - arr_1(Range(0, 2), Range::all());
  468. pow(diff, 2, diff);
  469. //第一行和第二行求和,即两点间距离的平方
  470. Mat add = diff(Range(0, 1), Range::all()) + diff(Range(1, 2), Range::all());
  471. float* p_add = add.ptr<float>(0);
  472. //遍历所有距离,如果小于阈值,则认为是局内点
  473. for (size_t i = 0; i < N; ++i)
  474. {
  475. if (p_add[i] < threshold) //初始 p_add[i]
  476. {
  477. right[i] = true;
  478. ++consensus_num;
  479. }
  480. else
  481. right[i] = false;
  482. }
  483. }
  484. else if (model == string("affine") || model == string("similarity"))
  485. {
  486. Mat match2_xy_change = T * arr_2; //计算在参考图像中的映射坐标
  487. Mat diff = match2_xy_change - arr_1;
  488. pow(diff, 2, diff);
  489. //第一行和第二行求和,计算特征点间的距离的平方
  490. Mat add = diff(Range(0, 1), Range::all()) + diff(Range(1, 2), Range::all());
  491. float* p_add = add.ptr<float>(0);
  492. for (size_t i = 0; i < N; ++i)
  493. {
  494. //如果小于阈值
  495. if (p_add[i] < threshold)
  496. {
  497. right[i] = true;
  498. ++consensus_num;
  499. }
  500. else
  501. right[i] = false;
  502. }
  503. }
  504. //判断当前一致集是否是优于之前最优一致集,并更新当前最优一致集个数
  505. if (consensus_num > most_consensus_num)
  506. {
  507. most_consensus_num = consensus_num;
  508. //把正确匹配的点赋予标签 1
  509. for (size_t i = 0; i < N; ++i)
  510. inliers[i] = right[i];
  511. }
  512. }
  513. //删除重复点对
  514. for (size_t i = 0; i < N - 1; ++i)
  515. {
  516. for (size_t j = i + 1; j < N; ++j)
  517. {
  518. if (inliers[i] && inliers[j])
  519. {
  520. if (p10[i] == p10[j] && p11[i] == p11[j] && p20[i] == p20[j] && p21[i] == p21[j])
  521. {
  522. inliers[j] = false;
  523. --most_consensus_num;
  524. }
  525. }
  526. }
  527. }
  528. //迭代结束,获得最优一致集合,根据这些最优一致集合计算出最终的变换关系 T
  529. Mat consensus_arr1, consensus_arr2; //经过迭代后最终确认正确匹配的点
  530. consensus_arr1.create(most_consensus_num, 2, CV_32FC1);
  531. consensus_arr2.create(most_consensus_num, 2, CV_32FC1);
  532. int k = 0;
  533. for (size_t i = 0; i < N; ++i)
  534. {
  535. if (inliers[i])
  536. {
  537. consensus_arr1.at<float>(k, 0) = p10[i];
  538. consensus_arr1.at<float>(k, 1) = p11[i];
  539. consensus_arr2.at<float>(k, 0) = p20[i];
  540. consensus_arr2.at<float>(k, 1) = p21[i];
  541. ++k;
  542. }
  543. }
  544. int num_ransac = (model == string("similarity") ? 2 : (model == string("affine") ? 3 : 4));
  545. if (k < num_ransac)
  546. CV_Error(CV_StsBadArg, "ransac模块删除错误点对后剩下正确点对个数不足以计算出变换关系矩阵!");
  547. //利用迭代后正确匹配点计算变换矩阵,为什么不是挑选 n 个点计算变换矩阵
  548. T = LMS(consensus_arr1, consensus_arr2, model, rmse);
  549. return T;
  550. }
  551. /********************该函数生成两幅图的棋盘网格图*************************/
  552. /*image_1表示参考图像
  553. image_2表示配准后的待配准图像
  554. chessboard_1表示image_1的棋盘图像
  555. chessboard_2表示image_2的棋盘图像
  556. mosaic_image表示image_1和image_2的镶嵌图像
  557. width表示棋盘网格大小
  558. */
  559. void myMatch::mosaic_map(const Mat& image_1, const Mat& image_2, Mat& chessboard_1, Mat& chessboard_2, Mat& mosaic_image, int width)
  560. {
  561. if (image_1.size != image_2.size)
  562. CV_Error(CV_StsBadArg, "mosaic_map模块输入两幅图大小必须一致!");
  563. //生成image_1的棋盘网格图
  564. chessboard_1 = image_1.clone();
  565. int rows_1 = chessboard_1.rows;
  566. int cols_1 = chessboard_1.cols;
  567. int row_grids_1 = cvFloor((double)rows_1 / width); //行方向网格个数
  568. int col_grids_1 = cvFloor((double)cols_1 / width); //列方向网格个数
  569. //指定区域像素赋值为零,便形成了棋盘图
  570. //第一幅图,第一行 2、4、6 像素值赋值零;第一幅图与第二幅图零像素位置交叉,以便两幅图交叉显示
  571. for (int i = 0; i < row_grids_1; i = i + 2)
  572. {
  573. for (int j = 1; j < col_grids_1; j = j + 2)
  574. {
  575. Range range_x(j * width, (j + 1) * width);
  576. Range range_y(i * width, (i + 1) * width);
  577. chessboard_1(range_y, range_x) = 0;
  578. }
  579. }
  580. for (int i = 1; i < row_grids_1; i = i + 2)
  581. {
  582. for (int j = 0; j < col_grids_1; j = j + 2)
  583. {
  584. Range range_x(j * width, (j + 1) * width);
  585. Range range_y(i * width, (i + 1) * width);
  586. chessboard_1(range_y, range_x) = 0;
  587. }
  588. }
  589. //生成image_2的棋盘网格图
  590. chessboard_2 = image_2.clone();
  591. int rows_2 = chessboard_2.rows;
  592. int cols_2 = chessboard_2.cols;
  593. int row_grids_2 = cvFloor((double)rows_2 / width);//行方向网格个数
  594. int col_grids_2 = cvFloor((double)cols_2 / width);//列方向网格个数
  595. //第二幅图,第一行 1、3、5 像素值赋值零
  596. for (int i = 0; i < row_grids_2; i = i + 2)
  597. {
  598. for (int j = 0; j < col_grids_2; j = j + 2)
  599. {
  600. Range range_x(j * width, (j + 1) * width);
  601. Range range_y(i * width, (i + 1) * width);
  602. chessboard_2(range_y, range_x) = 0;
  603. }
  604. }
  605. for (int i = 1; i < row_grids_2; i = i + 2)
  606. {
  607. for (int j = 1; j < col_grids_2; j = j + 2)
  608. {
  609. Range range_x(j * width, (j + 1) * width);
  610. Range range_y(i * width, (i + 1) * width);
  611. chessboard_2(range_y, range_x) = 0;
  612. }
  613. }
  614. //两个棋盘图进行叠加,显示配准效果
  615. mosaic_image = chessboard_1 + chessboard_2;
  616. }
  617. /*该函数对输入图像指定位置像素进行中值滤波,消除边缘拼接阴影*/
  618. /*image表示输入的图像
  619. position表示需要进行中值滤波的位置
  620. */
  621. inline void median_filter(Mat& image, const vector<vector<int>>& pos)
  622. {
  623. int channels = image.channels();
  624. switch (channels)
  625. {
  626. case 1://单通道
  627. for (auto beg = pos.cbegin(); beg != pos.cend(); ++beg)
  628. {
  629. int i = (*beg)[0];//y
  630. int j = (*beg)[1];//x
  631. uchar& pix_val = image.at<uchar>(i, j);
  632. vector<uchar> pixs;
  633. for (int row = -1; row <= 1; ++row)
  634. {
  635. for (int col = -1; col <= 1; ++col)
  636. {
  637. if (i + row >= 0 && i + row < image.rows && j + col >= 0 && j + col < image.cols)
  638. {
  639. pixs.push_back(image.at<uchar>(i + row, j + col));
  640. }
  641. }
  642. }
  643. //排序
  644. std::sort(pixs.begin(), pixs.end());
  645. pix_val = pixs[pixs.size() / 2];
  646. }
  647. break;
  648. case 3://3通道
  649. for (auto beg = pos.cbegin(); beg != pos.cend(); ++beg)
  650. {
  651. int i = (*beg)[0];//y
  652. int j = (*beg)[1];//x
  653. Vec3b& pix_val = image.at<Vec3b>(i, j);
  654. vector<cv::Vec3b> pixs;
  655. for (int row = -1; row <= 1; ++row)
  656. {
  657. for (int col = -1; col <= 1; ++col)
  658. {
  659. if (i + row >= 0 && i + row < image.rows && j + col >= 0 && j + col < image.cols)
  660. {
  661. pixs.push_back(image.at<Vec3b>(i + row, j + col));
  662. }
  663. }
  664. }
  665. //排序
  666. std::sort(pixs.begin(), pixs.end(),
  667. [pix_val](const Vec3b& a, const Vec3b& b)->bool {
  668. return sum((a).ddot(a))[0] < sum((b).ddot(b))[0];
  669. });
  670. pix_val = pixs[pixs.size() / 2];
  671. }
  672. break;
  673. default:break;
  674. }
  675. }
  676. /***************该函数把配准后的图像进行融合*****************/
  677. /*该函数功能主要是来对图像进行融合,以显示配准的效果
  678. *image_1表示参考图像
  679. *image_2表示待配准图像
  680. *T表示待配准图像到参考图像的转换矩阵
  681. *fusion_image表示参考图像和待配准图像融合后的图像
  682. *mosaic_image表示参考图像和待配准图像融合镶嵌后的图像,镶嵌图形是为了观察匹配效果
  683. *matched_image表示把待配准图像进行配准后的结果
  684. */
  685. void myMatch::image_fusion(const Mat& image_1, const Mat& image_2, const Mat T, Mat& fusion_image, Mat& matched_image)
  686. {
  687. //有关depth()的理解,详解:https://blog.csdn.net/datouniao1/article/details/113524784
  688. if (!(image_1.depth() == CV_8U && image_2.depth() == CV_8U))
  689. CV_Error(CV_StsBadArg, "image_fusion模块仅支持uchar类型图像!");
  690. if (image_1.channels() == 4 || image_2.channels() == 4)
  691. CV_Error(CV_StsBadArg, "image_fusion模块仅仅支持单通道或者3通道图像");
  692. int rows_1 = image_1.rows, cols_1 = image_1.cols;
  693. int rows_2 = image_2.rows, cols_2 = image_2.cols;
  694. int channel_1 = image_1.channels();
  695. int channel_2 = image_2.channels();
  696. //可以对:彩色-彩色、彩色-灰色、灰色-彩色、灰色-灰色的配准
  697. Mat image_1_temp, image_2_temp;
  698. if (channel_1 == 3 && channel_2 == 3)
  699. {
  700. image_1_temp = image_1;
  701. image_2_temp = image_2;
  702. }
  703. else if (channel_1 == 1 && channel_2 == 3)
  704. {
  705. image_1_temp = image_1;
  706. cvtColor(image_2, image_2_temp, CV_RGB2GRAY); //颜色空间转换,把彩色图转化为灰度图
  707. }
  708. else if (channel_1 == 3 && channel_2 == 1)
  709. {
  710. cvtColor(image_1, image_1_temp, CV_RGB2GRAY);
  711. image_2_temp = image_2;
  712. }
  713. else if (channel_1 == 1 && channel_2 == 1)
  714. {
  715. image_1_temp = image_1;
  716. image_2_temp = image_2;
  717. }
  718. //创建一个(3,3)float 矩阵 Mat_ 是一个模板类
  719. Mat T_temp = (Mat_<float>(3, 3) << 1, 0, cols_1, 0, 1, rows_1, 0, 0, 1);
  720. Mat T_1 = T_temp * T;
  721. //对参考图像和待配准图像进行变换
  722. Mat trans_1, trans_2;//same type as image_2_temp
  723. trans_1 = Mat::zeros(3 * rows_1, 3 * cols_1, image_1_temp.type()); //创建扩大后的矩阵
  724. image_1_temp.copyTo(trans_1(Range(rows_1, 2 * rows_1), Range(cols_1, 2 * cols_1))); //把image_1_temp中的数据复制到扩大后矩阵的对应位置
  725. warpPerspective(image_2_temp, trans_2, T_1, Size(3 * cols_1, 3 * rows_1), INTER_LINEAR, 0, Scalar::all(0));
  726. /*功能:把image_2_temp投射到一个新的视平面,即变形
  727. *image_2_temp为输入矩阵
  728. *trans_2为输出矩阵,尺寸和输入矩阵大小一致
  729. *T_1为变换矩阵,(3, 3)矩阵用于透视变换, (2, 2)用于线性变换, (1, 1)用于平移
  730. *warpPerspective函数功能是进行透视变换,T_1是(3,3)的透视变换矩阵
  731. *int flags=INTER_LINEAR为输出图像的插值方法
  732. *int borderMode=BORDER_CONSTANT,0 为图像边界的填充方式
  733. *const Scalar& borderValue=Scalar():边界的颜色设置,一般默认是0,Scalar::all(0)对影像边界外进行填充*/
  734. //使用简单的均值法进行图像融合
  735. Mat trans = trans_2.clone(); //把经过透视变换的image_2复制给trans
  736. int nRows = rows_1;
  737. int nCols = cols_1;
  738. int len = nCols;
  739. bool flag_1 = false;
  740. bool flag_2 = false;
  741. vector<vector<int>> positions; //保存边缘位置坐标
  742. switch (image_1_temp.channels())
  743. {
  744. case 1: //如果图像1是单通道的
  745. for (int i = 0; i < nRows; ++i)
  746. {
  747. uchar* ptr_1 = trans_1.ptr<uchar>(i + rows_1); //访问trans_1中的指定行像素值
  748. uchar* ptr = trans.ptr<uchar>(i + rows_1); //访问trans 中的指定行像素值
  749. for (int j = 0; j < nCols; ++j)
  750. {
  751. if (ptr[j + len] == 0 && ptr_1[j + len] != 0) //非重合区域
  752. {
  753. flag_1 = true;
  754. if (flag_2) //表明从重合区域过度到了非重合区域
  755. {
  756. for (int p = -1; p <= 1; ++p) //保存边界3x3区域像素
  757. {
  758. for (int q = -1; q <= 1; ++q)
  759. {
  760. vector<int> pos;
  761. pos.push_back(i + rows_1 + p);
  762. pos.push_back(j + cols_1 + q);
  763. positions.push_back(pos);//保存边缘位置坐标
  764. }
  765. }
  766. flag_2 = false;
  767. }
  768. ptr[j + len] = ptr_1[j + len];
  769. }
  770. else//对于重合区域
  771. {
  772. flag_2 = true;
  773. if (flag_1)//表明从非重合区域过度到了重合区域
  774. {
  775. for (int p = -1; p <= 1; ++p)//保存边界3x3区域像素
  776. {
  777. for (int q = -1; q <= 1; ++q)
  778. {
  779. vector<int> pos;
  780. pos.push_back(i + rows_1 + p);
  781. pos.push_back(j + cols_1 + q);
  782. positions.push_back(pos);//保存边缘位置坐标
  783. }
  784. }
  785. flag_1 = false;
  786. }
  787. ptr[j + len] = saturate_cast<uchar>(((float)ptr[j + len] + (float)ptr_1[j + len]) / 2);
  788. }
  789. }
  790. }
  791. break;
  792. case 3: //如果图像是三通道的
  793. len = len * image_1_temp.channels(); //3倍的列数
  794. for (int i = 0; i < nRows; ++i)
  795. {
  796. uchar* ptr_1 = trans_1.ptr<uchar>(i + rows_1); //访问trans_1中的指定行像素值
  797. uchar* ptr = trans.ptr<uchar>(i + rows_1); //访问trans 中的指定行像素值
  798. for (int j = 0; j < nCols; ++j)
  799. {
  800. int nj = j * image_1_temp.channels();
  801. //若两张影像对应列像素值不同(3通道),则是非重合区,该过程仅仅是为了使配准后的影像进行融合,而非配准
  802. if (ptr[nj + len] == 0 && ptr[nj + len + 1] == 0 && ptr[nj + len + 2] == 0 &&
  803. ptr_1[nj + len] != 0 && ptr_1[nj + len + 1] != 0 && ptr_1[nj + len + 2] != 0)
  804. {
  805. flag_1 = true;
  806. if (flag_2) //表明从重合区域过度到了非重合区域
  807. {
  808. for (int p = -1; p <= 1; ++p) //保存边界3x3区域像素
  809. {
  810. for (int q = -1; q <= 1; ++q)
  811. {
  812. vector<int> pos;
  813. pos.push_back(i + rows_1 + p);
  814. pos.push_back(j + cols_1 + q);
  815. positions.push_back(pos); //保存边缘位置坐标
  816. }
  817. }
  818. flag_2 = false;
  819. }
  820. ptr[nj + len] = ptr_1[nj + len];
  821. ptr[nj + len + 1] = ptr_1[nj + len + 1];
  822. ptr[nj + len + 2] = ptr_1[nj + len + 2];
  823. }
  824. else
  825. { //对于重合区域
  826. flag_2 = true;
  827. if (flag_1) //表明从非重合区域过度到了重合区域
  828. {
  829. for (int p = -1; p <= 1; ++p) //保存边界3x3区域像素
  830. {
  831. for (int q = -1; q <= 1; ++q)
  832. {
  833. vector<int> pos;
  834. pos.push_back(i + rows_1 + p);
  835. pos.push_back(j + cols_1 + q);
  836. positions.push_back(pos); //保存边缘位置坐标
  837. }
  838. }
  839. flag_1 = false;
  840. }
  841. ptr[nj + len] = saturate_cast<uchar>(((float)ptr[nj + len] + (float)ptr_1[nj + len]) / 2);
  842. ptr[nj + len + 1] = saturate_cast<uchar>(((float)ptr[nj + len + 1] + (float)ptr_1[nj + len + 1]) / 2);
  843. ptr[nj + len + 2] = saturate_cast<uchar>(((float)ptr[nj + len + 2] + (float)ptr_1[nj + len + 2]) / 2);
  844. }
  845. }
  846. }
  847. break;
  848. default:break;
  849. }
  850. //根据获取的边缘区域的坐标,对边缘像素进行中值滤波,消除边缘效应
  851. median_filter(trans, positions);
  852. //删除多余的区域
  853. Mat left_up = T_1 * (Mat_<float>(3, 1) << 0, 0, 1); //左上角
  854. Mat left_down = T_1 * (Mat_<float>(3, 1) << 0, rows_2 - 1, 1); //左下角
  855. Mat right_up = T_1 * (Mat_<float>(3, 1) << cols_2 - 1, 0, 1); //右上角
  856. Mat right_down = T_1 * (Mat_<float>(3, 1) << cols_2 - 1, rows_2 - 1, 1); //右下角
  857. //对于透视变换,需要除以一个因子
  858. left_up = left_up / left_up.at<float>(2, 0);
  859. left_down = left_down / left_down.at<float>(2, 0);
  860. right_up = right_up / right_up.at<float>(2, 0);
  861. right_down = right_down / right_down.at<float>(2, 0);
  862. //计算x,y坐标的范围
  863. float temp_1 = min(left_up.at<float>(0, 0), left_down.at<float>(0, 0));
  864. float temp_2 = min(right_up.at<float>(0, 0), right_down.at<float>(0, 0));
  865. float min_x = min(temp_1, temp_2);
  866. temp_1 = max(left_up.at<float>(0, 0), left_down.at<float>(0, 0));
  867. temp_2 = max(right_up.at<float>(0, 0), right_down.at<float>(0, 0));
  868. float max_x = max(temp_1, temp_2);
  869. temp_1 = min(left_up.at<float>(1, 0), left_down.at<float>(1, 0));
  870. temp_2 = min(right_up.at<float>(1, 0), right_down.at<float>(1, 0));
  871. float min_y = min(temp_1, temp_2);
  872. temp_1 = max(left_up.at<float>(1, 0), left_down.at<float>(1, 0));
  873. temp_2 = max(right_up.at<float>(1, 0), right_down.at<float>(1, 0));
  874. float max_y = max(temp_1, temp_2);
  875. int X_min = max(cvFloor(min_x), 0);
  876. int X_max = min(cvCeil(max_x), 3 * cols_1 - 1);
  877. int Y_min = max(cvFloor(min_y), 0);
  878. int Y_max = min(cvCeil(max_y), 3 * rows_1 - 1);
  879. if (X_min > cols_1)
  880. X_min = cols_1;
  881. if (X_max < 2 * cols_1 - 1)
  882. X_max = 2 * cols_1 - 1;
  883. if (Y_min > rows_1)
  884. Y_min = rows_1;
  885. if (Y_max < 2 * rows_1 - 1)
  886. Y_max = 2 * rows_1 - 1;
  887. //提取有价值区域
  888. Range Y_range(Y_min, Y_max + 1);
  889. Range X_range(X_min, X_max + 1);
  890. fusion_image = trans(Y_range, X_range);
  891. matched_image = trans_2(Y_range, X_range);
  892. Mat ref_matched = trans_1(Y_range, X_range);
  893. //生成棋盘网格图像
  894. /*Mat chessboard_1, chessboard_2;
  895. mosaic_map(trans_1(Y_range, X_range), trans_2(Y_range, X_range), chessboard_1, chessboard_2, mosaic_image, 100);*/
  896. /*cv::imwrite(".\\image_save\\参考图像棋盘图像.jpg", chessboard_1);
  897. cv::imwrite(".\\image_save\\待配准图像棋盘图像.jpg", chessboard_2);*/
  898. cv::imwrite(".\\image_save\\配准后的参考图像.jpg", ref_matched);
  899. cv::imwrite(".\\image_save\\配准后的待配准图像.jpg", matched_image);
  900. }
  901. /******该函数计算参考图像一个描述子和待配准图像所有描述子的欧式距离,并获得最近邻和次近邻距离,以及对应的索引*/
  902. /*sub_des_1表示参考图像的一个描述子
  903. *des_2表示待配准图像描述子
  904. *num_des_2值待配准图像描述子个数
  905. *dims_des指的是描述子维度
  906. *dis保存最近邻和次近邻距离
  907. *idx保存最近邻和次近邻索引
  908. */
  909. inline void min_dis_idx(const float* ptr_1, const Mat& des_2, int num_des2, int dims_des, float dis[2], int idx[2])
  910. {
  911. float min_dis1 = 1000, min_dis2 = 2000;
  912. int min_idx1, min_idx2;
  913. for (int j = 0; j < num_des2; ++j)
  914. {
  915. const float* ptr_des_2 = des_2.ptr<float>(j);
  916. float cur_dis = 0;
  917. for (int k = 0; k < dims_des; ++k)
  918. {
  919. float diff = ptr_1[k] - ptr_des_2[k];
  920. cur_dis += diff * diff;
  921. }
  922. if (cur_dis < min_dis1) {
  923. min_dis1 = cur_dis;
  924. min_idx1 = j;
  925. }
  926. else if (cur_dis >= min_dis1 && cur_dis < min_dis2) {
  927. min_dis2 = cur_dis;
  928. min_idx2 = j;
  929. }
  930. }
  931. dis[0] = sqrt(min_dis1); dis[1] = sqrt(min_dis2);
  932. idx[0] = min_idx1; idx[1] = min_idx2;
  933. }
  934. /*加速版本的描述子匹配,返回匹配点候选集函数,该加速版本比前面版本速度提升了3倍*/
  935. void myMatch::match_des(const Mat& des_1, const Mat& des_2, vector<vector<DMatch>>& dmatchs, DIS_CRIT dis_crite)
  936. {
  937. int num_des_1 = des_1.rows;
  938. int num_des_2 = des_2.rows;
  939. int dims_des = des_1.cols;
  940. vector<DMatch> match(2);
  941. //对于参考图像上的每一点,和待配准图像进行匹配
  942. if (dis_crite == 0) //欧几里得距离
  943. {
  944. for (int i = 0; i < num_des_1; ++i) //对于参考图像中的每个描述子
  945. {
  946. const float* ptr_des_1 = des_1.ptr<float>(i);
  947. float dis[2];
  948. int idx[2];
  949. min_dis_idx(ptr_des_1, des_2, num_des_2, dims_des, dis, idx);
  950. match[0].queryIdx = i;
  951. match[0].trainIdx = idx[0];
  952. match[0].distance = dis[0];
  953. match[1].queryIdx = i;
  954. match[1].trainIdx = idx[1];
  955. match[1].distance = dis[1];
  956. dmatchs.push_back(match);
  957. }
  958. }
  959. else if (dis_crite == 1)//cos距离
  960. {
  961. Mat trans_des2;
  962. transpose(des_2, trans_des2);
  963. double aa = (double)getTickCount();
  964. Mat mul_des = des_1 * trans_des2;
  965. //gemm(des_1, des_2, 1, Mat(), 0, mul_des, GEMM_2_T);
  966. double time1 = ((double)getTickCount() - aa) / getTickFrequency();
  967. cout << "cos距离中矩阵乘法花费时间: " << time1 << "s" << endl;
  968. for (int i = 0; i < num_des_1; ++i)
  969. {
  970. float max_cos1 = -1000, max_cos2 = -2000;
  971. int max_idx1, max_idx2;
  972. float* ptr_1 = mul_des.ptr<float>(i);
  973. for (int j = 0; j < num_des_2; ++j)
  974. {
  975. float cur_cos = ptr_1[j];
  976. if (cur_cos > max_cos1) {
  977. max_cos1 = cur_cos;
  978. max_idx1 = j;
  979. }
  980. else if (cur_cos <= max_cos1 && cur_cos > max_cos2) {
  981. max_cos2 = cur_cos;
  982. max_idx2 = j;
  983. }
  984. }
  985. match[0].queryIdx = i;
  986. match[0].trainIdx = max_idx1;
  987. match[0].distance = acosf(max_cos1);
  988. match[1].queryIdx = i;
  989. match[1].trainIdx = max_idx2;
  990. match[1].distance = acosf(max_cos2);
  991. dmatchs.push_back(match);
  992. }
  993. }
  994. }
  995. /*******************建立尺度直方图、ROM 直方图************************/
  996. void myMatch::scale_ROM_Histogram(const vector<DMatch>& matches, float* scale_hist, float* ROM_hist, int n)
  997. {
  998. int len = matches.size();
  999. //使用AutoBuffer分配一段内存,这里多出4个空间的目的是为了方便后面平滑直方图的需要
  1000. AutoBuffer<float> buffer((4 * len) + n + 4);
  1001. //X保存水平差分,Y保存数值差分,Mag保存梯度幅度,Ori保存梯度角度,W保存高斯权重
  1002. float* X = buffer, * Y = buffer + len, * Mag = Y, * Ori = Y + len, * W = Ori + len;
  1003. float* temp_hist = W + len + 2; //临时保存直方图数据
  1004. for (int i = 0; i < n; ++i)
  1005. temp_hist[i] = 0.f; //数据清零
  1006. }
  1007. /*******************该函数删除错误匹配点对,并完成匹配************************/
  1008. /*image_1表示参考图像,
  1009. image_2表示待配准图像
  1010. dmatchs表示最近邻和次近邻匹配点对
  1011. keys_1表示参考图像特征点集合
  1012. keys_2表示待配准图像特征点集合
  1013. model表示变换模型
  1014. right_matchs表示参考图像和待配准图像正确匹配点对
  1015. matched_line表示在参考图像和待配准图像上绘制连接线
  1016. 该函数返回变换模型参数
  1017. */
  1018. Mat myMatch::match(const Mat& image_1, const Mat& image_2, const vector<vector<DMatch>>& dmatchs, vector<KeyPoint> keys_1,
  1019. vector<KeyPoint> keys_2, string model, vector<DMatch>& right_matchs, Mat& matched_line, vector<DMatch>& init_matchs)
  1020. {
  1021. //获取初始匹配的关键点的位置
  1022. vector<Point2f> point_1, point_2;
  1023. for (size_t i = 0; i < dmatchs.size(); ++i) //增加一个一个0.8,正确匹配点数增加2
  1024. {
  1025. double dis_1 = dmatchs[i][0].distance; //distance对应的是特征点描述符的欧式距离
  1026. double dis_2 = dmatchs[i][1].distance;
  1027. //比率测试筛选误匹配点(初步筛选),如果满足则认为是有候选集中有正确匹配点
  1028. if ((dis_1 / dis_2) < dis_ratio3) //最近邻和次近邻距离比阈值
  1029. {
  1030. //queryIdx、trainIdx和distance是DMatch类中的一些属性 //pt是KeyPoint类中的成员,对应关键点的坐标
  1031. point_1.push_back(keys_1[dmatchs[i][0].queryIdx].pt); //queryIdx对应的是特征描述子的下标,也是对应特征点的下标
  1032. point_2.push_back(keys_2[dmatchs[i][0].trainIdx].pt); //trainIdx对应的是特征描述子的下标,也是对应特征点的下标
  1033. init_matchs.push_back(dmatchs[i][0]); //保存正确的dmatchs
  1034. }
  1035. }
  1036. cout << "距离比之后初始匹配点对个数是: " << init_matchs.size() << endl;
  1037. int min_pairs = (model == string("similarity") ? 2 : (model == string("affine") ? 3 : 4));
  1038. if (point_1.size() < min_pairs)
  1039. CV_Error(CV_StsBadArg, "match模块距离比阶段匹配特征点个数不足!");
  1040. //使用ransac算法再次对匹配点进行筛选,然后使用最后确定的匹配点计算变换矩阵的参数
  1041. vector<bool> inliers; //存放的是 bool 类型的数据,对应特征点
  1042. float rmse;
  1043. //homography是一个(3,3)矩阵,是待配准影像到参考影像的变换矩阵,初始误差阈值是 1.5
  1044. Mat homography = ransac(point_1, point_2, model, 1.5, inliers, rmse);
  1045. //提取出处正确匹配点对
  1046. int i = 0;
  1047. vector<Point2f> point_11, point_22;
  1048. vector<DMatch>::iterator itt = init_matchs.begin();
  1049. for (vector<bool>::iterator it = inliers.begin(); it != inliers.end(); ++it, ++itt)
  1050. {
  1051. if (*it) //如果是正确匹配点对
  1052. {
  1053. right_matchs.push_back(*itt);
  1054. // init_matchs 中匹配点对的存储顺序和 point_1 中特征点的存储顺序是一一对应的
  1055. point_11.push_back(point_1.at(i));
  1056. point_22.push_back(point_2.at(i));
  1057. }
  1058. ++i;
  1059. }
  1060. cout << "使用RANSAC删除错误点对,且返回正确匹配个数: " << right_matchs.size() << endl;
  1061. cout << "误差rmse: " << rmse << endl;
  1062. //绘制初始匹配点对连线图,此时初始匹配指的是经过 KnnMatch 筛选后的匹配
  1063. Mat initial_matched; //输出矩阵,类似画布
  1064. drawMatches(image_1, keys_1, image_2, keys_2, init_matchs, initial_matched,
  1065. Scalar(255, 0, 255), Scalar(0, 255, 0), vector<char>()); //该函数用于绘制特征点并对匹配的特征点进行连线
  1066. imwrite(".\\image_save\\初始匹配点对.jpg", initial_matched); //保存图片,第一个颜色控制连线,第二个颜色控制特征点
  1067. //绘制正确匹配点对连线图
  1068. drawMatches(image_1, keys_1, image_2, keys_2, right_matchs, matched_line,
  1069. Scalar(255, 0, 255), Scalar(0, 255, 0), vector<char>());
  1070. imwrite(".\\image_save\\正确匹配点对.jpg", matched_line);
  1071. //保存和显示检测到的特征点
  1072. Mat keys_image_1, keys_image_2; //输出矩阵,类似画布
  1073. drawKeypoints(image_1, keys_1, keys_image_1, Scalar(0, 255, 0)); //该函数用于绘制图像中的特征点
  1074. drawKeypoints(image_2, keys_2, keys_image_2, Scalar(0, 255, 0));
  1075. imwrite(".\\image_save\\参考图像检测到的特征点.jpg", keys_image_1);
  1076. imwrite(".\\image_save\\待配准图像检测到的.jpg", keys_image_2);
  1077. return homography;
  1078. }
  1079. myMatch::~myMatch()
  1080. {
  1081. }

5、 myDisplay.h

  1. #pragma
  2. #include<iostream>
  3. #include<opencv2\core\core.hpp>
  4. #include<opencv2\features2d\features2d.hpp>
  5. #include<vector>
  6. using namespace cv;
  7. using namespace std;
  8. class myDisplay
  9. {
  10. public:
  11. myDisplay() {}
  12. void mosaic_pyramid(const vector<vector<Mat>>& pyramid, Mat& pyramid_image, int nOctaceLayers, string str);
  13. void write_mosaic_pyramid(const vector<vector<Mat>>& gauss_pyr_1, const vector<vector<Mat>>& dog_pyr_1,
  14. const vector<vector<Mat>>& gauss_pyr_2, const vector<vector<Mat>>& dog_pyr_2, int nOctaveLayers);
  15. //没用到,后文没有对其进行定义
  16. void write_keys_image(vector<KeyPoint>& keypoints_1, vector<KeyPoint>& keypoints_2,
  17. const Mat& image_1, const Mat& image_2, Mat& image_1_keys, Mat& image_2_keys, bool double_size);
  18. };

6、 myDisplay.cpp

  1. #include "myDisplay.h"
  2. #include<opencv2\highgui\highgui.hpp>
  3. #include<vector>
  4. #include<sstream>
  5. /***************************该函数把金字塔放在一副图像上(包络高斯金字塔和DOG金字塔)******************/
  6. /*pyramid表示高斯金字塔或者DOG金字塔
  7. pyramid_image表示生成的金字塔图像
  8. nOctaveLayers表示每组中间层数,默认是3
  9. str表示是高斯金字塔还是DOG金字塔
  10. */
  11. void myDisplay::mosaic_pyramid(const vector<vector<Mat>>& pyramid, Mat& pyramid_image, int nOctaceLayers, string str)
  12. {
  13. //获得每组金字塔图像大小
  14. vector<vector<int>> temp_size;
  15. for (auto beg = pyramid.cbegin(); beg != pyramid.cend(); ++beg)
  16. {
  17. vector<int> temp_vec;
  18. int rows = (*beg)[0].rows;
  19. int cols = (*beg)[0].cols;
  20. temp_vec.push_back(rows);
  21. temp_vec.push_back(cols);
  22. temp_size.push_back(temp_vec);
  23. }
  24. //计算最后生成的金字塔图像pyramid_image的大小
  25. int total_rows = 0, total_cols = 0;
  26. for (auto beg = temp_size.begin(); beg != temp_size.end(); ++beg)
  27. {
  28. total_rows = total_rows + (*beg)[0];//获取行大小
  29. if (beg == temp_size.begin()) {
  30. if (str == string("高斯金字塔"))
  31. total_cols = (nOctaceLayers + 3) * ((*beg)[1]);//获取列大小
  32. else if (str == string("DOG金字塔"))
  33. total_cols = (nOctaceLayers + 2) * ((*beg)[1]);//获取列大小
  34. }
  35. }
  36. pyramid_image.create(total_rows, total_cols, CV_8UC1);
  37. int i = 0, accumulate_row = 0;
  38. for (auto beg = pyramid.cbegin(); beg != pyramid.cend(); ++beg, ++i)
  39. {
  40. int accumulate_col = 0;
  41. accumulate_row = accumulate_row + temp_size[i][0];
  42. for (auto it = (*beg).cbegin(); it != (*beg).cend(); ++it)
  43. {
  44. accumulate_col = accumulate_col + temp_size[i][1];
  45. Mat temp(pyramid_image, Rect(accumulate_col - temp_size[i][1], accumulate_row - temp_size[i][0], it->cols, it->rows));
  46. Mat temp_it;
  47. normalize(*it, temp_it, 0, 255, NORM_MINMAX, CV_32FC1);
  48. convertScaleAbs(temp_it, temp_it, 1, 0);
  49. temp_it.copyTo(temp);
  50. }
  51. }
  52. }
  53. /**************************该函数保存拼接后的高斯金字塔和DOG金字塔图像**************************/
  54. /*gauss_pyr_1表示参考高斯金字塔
  55. dog_pyr_1表示参考DOG金字塔
  56. gauss_pyr_2表示待配准高斯金字塔
  57. dog_pyr_2表示待配准DOG金字塔
  58. nOctaveLayers表示金字塔每组中间层数
  59. */
  60. void myDisplay::write_mosaic_pyramid(const vector<vector<Mat>>& gauss_pyr_1, const vector<vector<Mat>>& dog_pyr_1,
  61. const vector<vector<Mat>>& gauss_pyr_2, const vector<vector<Mat>>& dog_pyr_2, int nOctaveLayers)
  62. {
  63. //显示参考和待配准高斯金字塔图像
  64. Mat gauss_image_1, gauss_image_2;
  65. mosaic_pyramid(gauss_pyr_1, gauss_image_1, nOctaveLayers, string("高斯金字塔"));
  66. mosaic_pyramid(gauss_pyr_2, gauss_image_2, nOctaveLayers, string("高斯金字塔"));
  67. imwrite(".\\image_save\\参考图像高斯金字塔.jpg", gauss_image_1);
  68. imwrite(".\\image_save\\待配准图像高斯金字塔.jpg", gauss_image_2);
  69. //显示参考和待配准DOG金字塔图像
  70. Mat dog_image_1, dog_image_2;
  71. mosaic_pyramid(dog_pyr_1, dog_image_1, nOctaveLayers, string("DOG金字塔"));
  72. mosaic_pyramid(dog_pyr_2, dog_image_2, nOctaveLayers, string("DOG金字塔"));
  73. imwrite(".\\image_save\\参考图像DOG金字塔.jpg", dog_image_1);
  74. imwrite(".\\image_save\\待配准图像DOG金字塔.jpg", dog_image_2);
  75. }

7、 main.cpp

  1. #include"mySift.h"
  2. #include"myDisplay.h"
  3. #include"myMatch.h"
  4. #include<direct.h>
  5. #include<opencv2\highgui\highgui.hpp>
  6. #include<opencv2\calib3d\calib3d.hpp>
  7. #include<opencv2\imgproc\imgproc.hpp>
  8. #include<fstream>
  9. #include<stdlib.h>
  10. #include<direct.h>
  11. int main(int argc, char* argv[])
  12. {
  13. /********************** 1、读入数据 **********************/
  14. Mat image_1 = imread("..\\test_data\\perspective_graf_1.ppm", -1);
  15. Mat image_2 = imread("..\\test_data\\perspective_graf_2.ppm", -1);
  16. string change_model = "perspective"; //affine为仿射变换,初始为perspective
  17. string folderPath = ".\\image_save";
  18. _mkdir(folderPath.c_str());
  19. double total_count_beg = (double)getTickCount(); //算法运行总时间开始计时
  20. mySift sift_1(0, 3, 0.04, 10, 1.6, true); //类对象
  21. /********************** 1、参考图像特征点检测和描述 **********************/
  22. vector<vector<Mat>> gauss_pyr_1, dog_pyr_1; //高斯金字塔和高斯差分金字塔
  23. vector<KeyPoint> keypoints_1; //特征点
  24. vector<vector<vector<float>>> all_cell_contrasts_1; //所有尺度层中所有单元格的对比度
  25. vector<vector<float>> average_contrast_1; //所有尺度层中多有单元格的平均对比度
  26. vector<vector<int>> n_cells_1; //所有尺度层,每一尺度层中所有单元格所需特征数
  27. vector<int> num_cell_1; //当前尺度层中所有单元格中的所需特征数
  28. vector<vector<int>> available_n_1; //所有尺度层,每一尺度层中所有单元格可得到特征数
  29. vector<int> available_num_1; //一个尺度层中所有单元格中可用特征数量
  30. vector<KeyPoint> final_keypoints1; //第一次筛选结果
  31. vector<KeyPoint> Final_keypoints1; //第二次筛选结果
  32. vector<KeyPoint> Final_Keypoints1; //第三次筛选结果
  33. Mat descriptors_1; //特征描述子
  34. double detect_1 = (double)getTickCount(); //特征点检测运行时间开始计时
  35. sift_1.detect(image_1, gauss_pyr_1, dog_pyr_1, keypoints_1, all_cell_contrasts_1,
  36. average_contrast_1, n_cells_1, num_cell_1, available_n_1, available_num_1, final_keypoints1, Final_keypoints1, Final_Keypoints1); //特征点检测
  37. cout << "参考图像检测出的总特征数 =" << keypoints_1.size() << endl;
  38. //getTickFrequency() 返回值为一秒的计时周期数,二者比值为特征点检测时间
  39. double detect_time_1 = ((double)getTickCount() - detect_1) / getTickFrequency();
  40. cout << "参考图像特征点检测时间是: " << detect_time_1 << "s" << endl;
  41. double comput_1 = (double)getTickCount();
  42. vector<Mat> sar_harris_fun_1;
  43. vector<Mat> amplit_1;
  44. vector<Mat> orient_1;
  45. sift_1.comput_des(gauss_pyr_1, keypoints_1, amplit_1, orient_1, descriptors_1);
  46. double comput_time_1 = ((double)getTickCount() - comput_1) / getTickFrequency();
  47. cout << "参考图像特征点描述时间是: " << comput_time_1 << "s" << endl;
  48. /********************** 1、待配准图像特征点检测和描述 **********************/
  49. vector<vector<Mat>> gauss_pyr_2, dog_pyr_2;
  50. vector<KeyPoint> keypoints_2;
  51. vector<vector<vector<float>>> all_cell_contrasts_2; //所有尺度层中所有单元格的对比度
  52. vector<vector<float>> average_contrast_2; //所有尺度层中多有单元格的平均对比度
  53. vector<vector<int>> n_cells_2; //所有尺度层,每一尺度层中所有单元格所需特征数
  54. vector<int> num_cell_2; //当前尺度层中所有单元格中的所需特征数
  55. vector<vector<int>> available_n_2; //所有尺度层,每一尺度层中的一个单元格可得到特征数
  56. vector<int> available_num_2; //一个尺度层中所有单元格中可用特征数量
  57. vector<KeyPoint> final_keypoints2; //第一次筛选结果
  58. vector<KeyPoint> Final_keypoints2; //第二次筛选结果
  59. vector<KeyPoint> Final_Keypoints2; //第三次筛选结果
  60. Mat descriptors_2;
  61. double detect_2 = (double)getTickCount();
  62. sift_1.detect(image_2, gauss_pyr_2, dog_pyr_2, keypoints_2, all_cell_contrasts_2,
  63. average_contrast_2, n_cells_2, num_cell_2, available_n_2, available_num_2, final_keypoints2, Final_keypoints2, Final_Keypoints2);
  64. cout << "待配准图像检测出的总特征数 =" << keypoints_2.size() << endl;
  65. double detect_time_2 = ((double)getTickCount() - detect_2) / getTickFrequency();
  66. cout << "待配准图像特征点检测时间是: " << detect_time_2 << "s" << endl;
  67. double comput_2 = (double)getTickCount();
  68. vector<Mat> sar_harris_fun_2;
  69. vector<Mat> amplit_2;
  70. vector<Mat> orient_2;
  71. sift_1.comput_des(gauss_pyr_2, keypoints_2, amplit_2, orient_2, descriptors_2);
  72. double comput_time_2 = ((double)getTickCount() - comput_2) / getTickFrequency();
  73. cout << "待配准特征点描述时间是: " << comput_time_2 << "s" << endl;
  74. /********************** 1、最近邻与次近邻距离比匹配,两幅影像进行配准 **********************/
  75. myMatch mymatch;
  76. double match_time = (double)getTickCount(); //影像配准计时开始
  77. //knnMatch函数是DescriptorMatcher类的成员函数,FlannBasedMatcher是DescriptorMatcher的子类
  78. Ptr<DescriptorMatcher> matcher1 = new FlannBasedMatcher;
  79. Ptr<DescriptorMatcher> matcher2 = new FlannBasedMatcher;
  80. vector<vector<DMatch>> dmatchs; //vector<DMatch>中存放的是一个描述子可能匹配的候选集
  81. vector<vector<DMatch>> dmatch1;
  82. vector<vector<DMatch>> dmatch2;
  83. matcher1->knnMatch(descriptors_1, descriptors_2, dmatchs, 2);
  84. cout << "距离比之前初始匹配点对个数是:" << dmatchs.size() << endl;
  85. Mat matched_lines; //同名点连线
  86. vector<DMatch> init_matchs, right_matchs; //用于存放正确匹配的点
  87. //该函数返回的是空间映射模型参数
  88. Mat homography = mymatch.match(image_1, image_2, dmatchs, keypoints_1, keypoints_2, change_model, right_matchs, matched_lines, init_matchs);
  89. double match_time_2 = ((double)getTickCount() - match_time) / getTickFrequency();
  90. cout << "特征点匹配花费时间是: " << match_time_2 << "s" << endl;
  91. cout << change_model << "变换矩阵是:" << endl;
  92. cout << homography << endl;
  93. /********************** 1、把正确匹配点坐标写入文件中 **********************/
  94. ofstream ofile;
  95. ofile.open(".\\position.txt"); //创建文件
  96. for (size_t i = 0; i < right_matchs.size(); ++i)
  97. {
  98. ofile << keypoints_1[right_matchs[i].queryIdx].pt << " "
  99. << keypoints_2[right_matchs[i].trainIdx].pt << endl;
  100. }
  101. /********************** 1、图像融合 **********************/
  102. double fusion_beg = (double)getTickCount();
  103. Mat fusion_image, mosaic_image, regist_image;
  104. mymatch.image_fusion(image_1, image_2, homography, fusion_image, regist_image);
  105. imwrite(".\\image_save\\融合后的图像.jpg", fusion_image);
  106. double fusion_time = ((double)getTickCount() - fusion_beg) / getTickFrequency();
  107. cout << "图像融合花费时间是: " << fusion_time << "s" << endl;
  108. double total_time = ((double)getTickCount() - total_count_beg) / getTickFrequency();
  109. cout << "总花费时间是: " << total_time << "s" << endl;
  110. /********************** 1、生成棋盘图,显示配准结果 **********************/
  111. //生成棋盘网格图像
  112. Mat chessboard_1, chessboard_2, mosaic_images;
  113. Mat image1 = imread(".\\image_save\\配准后的参考图像.jpg", -1);
  114. Mat image2 = imread(".\\image_save\\配准后的待配准图像.jpg", -1);
  115. mymatch.mosaic_map(image1, image2, chessboard_1, chessboard_2, mosaic_images, 50);
  116. imwrite(".\\image_save\\参考图像棋盘图像.jpg", chessboard_1);
  117. imwrite(".\\image_save\\待配准图像棋盘图像.jpg", chessboard_2);
  118. imwrite(".\\image_save\\两幅棋盘图像叠加.jpg", mosaic_images);
  119. return 0;
  120. }

四、SIFT 算法实验结果

1、实验数据

**说明:该数据是从网上下载的两个时相影像,左侧为旧时相影像,右侧为新时相影像; **

2、实验结果

(1)特征点检测结果

(2)最终匹配结果

(3)配准效果

说明:把两张图像交叉重叠在一起,可以观察其配准效果;

** 五、配置说明**

** 该结果是在 VS2019 + opencv4.4.0 + Debug x64 环境下跑出来的;**

** **如果感觉复制麻烦,完整工程见:SIFT算法C++代码实现-C/C++文档类资源-CSDN下载


本文转载自: https://blog.csdn.net/weixin_47156401/article/details/122367593
版权归原作者 一米九零小胖子 所有, 如有侵权,请联系我们删除。

“SIFT算法详解(附有完整代码)”的评论:

还没有评论