opencv-自定义harris角点检测
关于harris角点检测的原理以及matlab版本,请移步https://www.cnblogs.com/klitech/p/5779600.html
小白初学,这里采用opencv实现之,把自己遇到的疑问一一表述出来,以备后用。
疑问1. CV_32FC1,CV_32FC(6)是什么意思?
CV_<bit_depth>(S|U|F)C<number_of_channels>
- bit_depth,可取的值为8,16,32,64.它表示一个像素所占用的bite数
- S|U|F, S--- signed int, U--- unsigned int, F---float
- C<number_of_channels> 通道数,灰度图像取值1,rgb图像取值3
疑问2. Mat::zeros的两种初始化
- Mat::zeros(int rows, int cols, int type)
- Mat::zeros(Size size,int type)
第一种形式,返回特定尺寸与类型的零矩阵,比如 Mat A = Mat::zeros(3,3,CV_32FC1);
第二种形式,程序中采用的方式,Mat::zeros(src.size(), CV_32FC(6));
我的理解是这两种形式实质一样
疑问3. cornerEigenValsAndVecs()使用方法
函数原型, cornerEigenValsAndVecs( InputArray src, OutputArray dst,
int blockSize, int ksize,
int borderType = BORDER_DEFAULT );
- src 图像类型应该为单通道,或者float
- dst 图像类型应该为CV_32FC(6),包含2个特征值,以及对应的2个2维向量,总计6个结果。
- blocksize 邻域大小
- ksize 函数采用sobel算子
- borderType 取默认BORDER_DEFAULT
函数调用参看后面的程序。
1 #include <opencv2/opencv.hpp>
2 #include <iostream>
3 #include <math.h>
4 using namespace cv;
5 using namespace std;
6 Mat src, gray_src;
7 Mat harris_dst, harrisRspImg;
8 double harris_min_rsp;
9 double harris_max_rsp;
10 int qualityLevel = 30;
11 const char* harris_win = "Custom Harris Corners Dector";
12 int max_count = 100;
13 void CustomHarris_Demo(int, void *);
14
15 int main()
16 {
17
18 src = imread("D:/1.png");
19 if (src.empty())
20 {
21 cout << "could not load image..." << endl;
22 return -1;
23 }
24 namedWindow("input_image", CV_WINDOW_AUTOSIZE);
25 imshow("input_image", src);
26 cvtColor(src, gray_src, COLOR_BGR2GRAY);
27 // 计算特征值
28 int blockSize = 3;
29 int ksize = 3;
30 double k = 0.04;
31
32 harris_dst = Mat::zeros(src.size(), CV_32FC(6)); //6通道
33 harrisRspImg = Mat::zeros(src.size(), CV_32FC1);
34 cornerEigenValsAndVecs(gray_src, harris_dst, blockSize, ksize, 4);
35 //计算响应
36 for (int row = 0; row < harris_dst.rows; row++)
37 {
38 for (int col = 0; col < harris_dst.cols; col++)
39 {
40 double lambda1 = harris_dst.at<Vec6f>(row, col)[0];
41 double lambda2 = harris_dst.at<Vec6f>(row, col)[1];
42 harrisRspImg.at<float>(row, col) = lambda1 * lambda2 - k*pow((lambda1 + lambda2), 2);
43 }
44 }
45 minMaxLoc(harrisRspImg, &harris_min_rsp, &harris_max_rsp, 0, 0, Mat());//求最大最小响应
46 namedWindow(harris_win, CV_WINDOW_AUTOSIZE);
47 createTrackbar("Quality Value", harris_win, &qualityLevel, max_count, CustomHarris_Demo);
48 CustomHarris_Demo(0, 0);
49 waitKey(0);
50 return 0;
51 }
52 void CustomHarris_Demo(int, void*) {
53 if (qualityLevel < 10) {
54 qualityLevel = 10;
55 }
56 Mat resultImg = src.clone();
57 float t = harris_min_rsp + (((double)qualityLevel) / max_count)*(harris_max_rsp - harris_min_rsp);
58 for (int row = 0; row < src.rows; row++) {
59 for (int col = 0; col < src.cols; col++) {
60 float v = harrisRspImg.at<float>(row, col);
61 if (v > t) {
62 circle(resultImg, Point(col, row), 2, Scalar(0, 0, 255), 2, 8, 0);
63 }
64 }
65 }
66
67 imshow(harris_win, resultImg);
68 }