Harris与ShiTomasi角点检测

#include "stdafx.h"
#include 
#include 
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;
using namespace std;

//全局变量
Mat src, src_gray, dst_norm_scaled;
int thresh = 110;
int max_thresh = 150;

int maxCorners = 23;
int maxTrackbar = 100;

char* source_window = "Source image";
char* corners_window = "Corners detected";

void cornerHarris_demo(int, void*);
void cornerShiTomasi_demo(int, void*);

int main()
{
	src = imread("C:\\哀.jpg", 1);
	cvtColor(src, src_gray, CV_BGR2GRAY);

	//创建窗口和滑动条
	namedWindow(source_window, CV_WINDOW_AUTOSIZE);
	createTrackbar("Harris: ", source_window, &thresh, max_thresh, cornerHarris_demo);
	createTrackbar("ShiTomasi:", source_window, &maxCorners, maxTrackbar, cornerShiTomasi_demo);

	namedWindow(corners_window, CV_WINDOW_AUTOSIZE);
	namedWindow(source_window, CV_WINDOW_AUTOSIZE);

	cornerHarris_demo(0, 0);
	cornerShiTomasi_demo(0, 0);


	waitKey(0);
	return(0);
}

void cornerHarris_demo(int, void*)
{
	Mat dst, dst_norm;
	dst = Mat::zeros(src.size(), CV_32FC1);
	///参数
	int blockSize = 2;
	int apertureSize = 3;
	double k = 0.04;
	///检测角点
	cornerHarris(src_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT);
	/// 标准化
	normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat());
	convertScaleAbs(dst_norm, dst_norm_scaled);
	/// 画出角点
	for (int j = 0; j < dst_norm.rows; j++)
	{
		for (int i = 0; i < dst_norm.cols; i++)
		{
			if ((int)dst_norm.at(j, i) > thresh)
			{
				circle(dst_norm_scaled, Point(i, j), 5, Scalar(0), -1, 8, 0);
				circle(src, Point(i, j), 5, Scalar(255, 0, 0), -1, 8, 0);
			}
		}
	}
	/// 显示结果
	imshow(corners_window, dst_norm_scaled);
	imshow(source_window, src);
}

void cornerShiTomasi_demo(int, void*)
{
	if (maxCorners < 1) { maxCorners = 1; }
	/// Shi-Tomasi算法的参数
	vector corners;
	double qualityLevel = 0.01;
	double minDistance = 10;
	int blockSize = 3;
	bool useHarrisDetector = false;
	double k = 0.04;
	/// 拷贝原图像
	Mat cormat;
	///应用角点检测:检测图中的强角点
	goodFeaturesToTrack(src_gray,
		corners,
		maxCorners,
		qualityLevel,
		minDistance,
		Mat(),
		blockSize,
		useHarrisDetector,
		k);
	/// 画出被检测到的角点
	for (int i = 0; i < corners.size(); i++) {
		circle(dst_norm_scaled, corners[i], 5, Scalar(255), 2, 8, 0);
		circle(src, corners[i], 4, Scalar(0, 255, 0), 2, 8, 0);
	}

	//显示结果
	imshow(corners_window, dst_norm_scaled);
	imshow(source_window, src);
}

结果:
蓝色点为Harris算法检测到的角点;绿色点为ShiTomasi算法检测到的角点
Harris与ShiTomasi角点检测_第1张图片
Harris与ShiTomasi角点检测_第2张图片
参考:毛星云 《OpenCV3编程入门》

你可能感兴趣的:(C++,opencv,图像处理)