opencvC++学习15线性滤波:

卷积概念

卷积是图像处理中一个操作,是kernel在图像的每个像素上的操作。

Kernel本质上一个固定大小的矩阵数组,其中心点称为锚点(anchor point)


卷积如何工作

把kernel放到像素数组之上,求锚点周围覆盖的像素乘积之和(包括锚点),用来替换锚点覆盖下像素点值称为卷积处理。数学表达如下:



常见算子

Robert算子


Sobel算子


拉普拉斯算子

代码:

#include <opencv2\opencv.hpp>

using namespace cv;
using namespace std;


Mat src, gray_src, dst;

int main()
{
	src = imread("D:/opencvSRC/test.jpg");
	if (!src.data) {

		printf("load image error!\n");
		return -1;
	}
	namedWindow("src", CV_WINDOW_AUTOSIZE);
	imshow("src", src);

	// Robert X 方向
	Mat kernel_x =( Mat_<int>(2, 2) << 1, 0, 0, -1);
	filter2D(src, dst, src.depth(), kernel_x, Point(-1, -1), 0.0, 4);
	imshow("RobertX", dst);
	// Robert Y 方向
	Mat kernel_y = (Mat_<int>(2, 2) << 0, 1, -1,0);
	filter2D(src, dst, src.depth(), kernel_y, Point(-1, -1), 0.0, 4);
	imshow("RobertY", dst);

	// Sobel X 方向
	 Mat kernel_sx = (Mat_<int>(3, 3) << -1, 0, 1, -2,0,2,-1,0,1);
	 filter2D(src, dst, -1, kernel_sx, Point(-1, -1), 0.0);
	 imshow("SobelX", dst);
	// Sobel Y 方向
	 //Mat yimg;
	 Mat kernel_sy = (Mat_<int>(3, 3) << -1, -2, -1, 0,0,0, 1,2,1);
	 filter2D(src, dst, -1, kernel_sy, Point(-1, -1), 0.0);
	 imshow("SobelY", dst);

	 // 拉普拉斯算子
	 Mat kernel_ly = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0);
	 filter2D(src, dst, -1, kernel_ly, Point(-1, -1), 0.0);
	 imshow("LP", dst);

	 //自定义卷积模糊
	 int c = 0;
	 int index = 0;
	 int ksize = 0;
	 while (true) {
		 c = waitKey(500);
		 if ((char)c == 27) {// ESC 
			 break;
		 }
		 ksize = 5 + (index % 8) * 2;
		 Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize * ksize);
		 filter2D(src, dst, -1, kernel, Point(-1, -1));
		 index++;
		 imshow("out", dst);
	 }

	waitKey(0);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/xiansong1005/article/details/80731333