【VC++、OpenCV3.4】自定义线性滤波——卷积操作

卷积公式:

H(x,y)=\sum _{i=0}^{M_{i-1}}\sum_{j=0}^{M_{j-1}}I(x+i-a_{i},y+j-a_{j})K(i,j)

卷积的作用:模糊图像、提取边缘、图像增强(锐化)等。

常见卷积核算子:Robert算子,对45度和135度的像素变化敏感。

【VC++、OpenCV3.4】自定义线性滤波——卷积操作_第1张图片

Sobel算子:分别对水平方向和数值方向的像素变化敏感

【VC++、OpenCV3.4】自定义线性滤波——卷积操作_第2张图片

拉普拉斯算子:用于边缘提取

【VC++、OpenCV3.4】自定义线性滤波——卷积操作_第3张图片

#include
#include
#include


using namespace cv;

Mat src, dst, dst1, dst2, dst3,dst4;
const String path = "C:\\Users\\admin\\Desktop\\demo.jpg";
const String Output = "Src window";
const String Output1 = "Robert window";
const String Output2 = "Sobel window";
const String Output21 = "Sobel1 window";
const String Output3 = "Laplace window";

int main(int argv, char** argc) {

	src = imread(path, IMREAD_REDUCED_COLOR_2);
	if (!src.data)
	{
		printf("Could not load the pic demo...");
		return false;
	}
	namedWindow(Output, CV_WINDOW_AUTOSIZE);
	

	Mat kernel1 = (Mat_(2, 2) << 1, 0, 0, 1);
	Mat kernel2 = (Mat_(2, 2) << 0, 1, 1, 0);
	Mat kernel3 = (Mat_(3, 3) << -1,0,1,-2,0,2,-1,0,1);
	Mat kernel4 = (Mat_(3, 3) << -1,-2 ,-1, 0, 0,0, 1, 2, 1);
	Mat kernel5 = (Mat_(3, 3) << 0, -1, 0, -1, 4,-1, 0, -1, 0);
	cvtColor(src, src, CV_BGR2GRAY);
	imshow(Output, src);
	//Robert
	filter2D(src, dst, -1, kernel2, Point(-1, -1));
	namedWindow(Output1, CV_WINDOW_AUTOSIZE);
	imshow(Output1, dst);
	//Sobel
	filter2D(src, dst2, -1, kernel3, Point(-1, -1));
	namedWindow(Output2, CV_WINDOW_AUTOSIZE);
	imshow(Output2, dst2);
	//Sobel1
	filter2D(src, dst3, -1, kernel4, Point(-1, -1));
	namedWindow(Output21, CV_WINDOW_AUTOSIZE);
	imshow(Output21, dst3);
	//Laplace

	filter2D(src, dst4, -1, kernel5, Point(-1, -1));
	namedWindow(Output3, CV_WINDOW_AUTOSIZE);
	imshow(Output3, dst4);
	
	waitKey(0);
	return 0;
}

效果:

【VC++、OpenCV3.4】自定义线性滤波——卷积操作_第4张图片

卷积:

	int c = 0;
	int ksize = 3;
	int index = 0;
	namedWindow(Output4, CV_WINDOW_AUTOSIZE);
	while (true)
	{
		waitKey(500);
		if ((char) c==27)//ESC
		{
			break;
		}
		ksize = 4 + (index % 5) * 2 + 1;
		Mat kernels = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize*ksize);
		filter2D(src, dst, -1, kernels, Point(-1, -1));
		index++;
		imshow(Output4, dst);
	}

【VC++、OpenCV3.4】自定义线性滤波——卷积操作_第5张图片

你可能感兴趣的:(OPENCV)