自定义线性滤波

1、卷积概念;
2、常见算子;
3、自定义卷积模糊;
4、代码演示;

卷积

1、图像卷积操作可以模糊图像, 降低一幅图像的噪声(降噪);
2、卷积是图像处理中的一个操作,是kernel(卷积核)在图像的每个像素上的操作,Kernel本质上是一个固定大小的矩阵数组,其中心点称为锚点(anchor point)
3、卷积计算方法:卷积核与图像矩阵依次相乘,取平均值作为锚点覆盖下像素点的像素值;从左到右,从上到下,依次做卷积,完成对整幅图像的卷积操作;

4、卷积的三个作用:①模糊图像;②提取边缘;③图像增显(锐化)

常见卷积算子(常见卷积核)

Robert算子:2*2算子

Sobel算子:边缘检测中常用

拉普拉斯算子:边缘检测中常用

自定义卷积模糊

-1 默认与原图一样,卷积核一般奇数

Code

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
   
	Mat src, dst;
	
	
	src = imread("C:\\Users\\hello\\Desktop\\1.jpg");
	if (!src.data)
	{
   
		cout << "could not load the image..." << endl;
		return -1;
	}
	namedWindow("input image", CV_WINDOW_AUTOSIZE);
	imshow("input image", src);
	char OUTPUT_WIN[] = "Robert X";
	namedWindow(OUTPUT_WIN, CV_WINDOW_AUTOSIZE);

	//X方向 Robert算子
	Mat robert_x = (Mat_<int>(2, 2) << 1, 0, 0, -1);  //一个2 * 2的矩阵
	filter2D(src, dst, -1, robert_x, Point(-1, -1));
	imshow(OUTPUT_WIN, dst);
	//Y方向 Robert算子
	Mat ying;
	Mat robert_y = (Mat_<int>(2, 2) << 0, 1, -1, 0);  //一个2 * 2的矩阵
	filter2D(src, ying, -1, robert_y, Point(-1, -1));
	imshow("Robert Y", ying);

	//Sobel算子
	Mat sx, sy;
	Mat Sobel_X = (Mat_<int>(3, 3) << -1, 0, 1, -2, 0, 2, -1, 0, 1); //1个3 * 3 矩阵 体现X方向差异
	Mat Sobel_Y = (Mat_<int>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1); //1个3 * 3 矩阵 体现Y方向差异
	filter2D(src, sx, -1, Sobel_X, Point(-1, -1));
	filter2D(src, sy, -1, Sobel_Y);
	imshow("sobel x", sx);
	imshow("sobel y", sy);

	//Laplace算子:边缘检测算子,可以得到图像的整个差异 4个0的laplace算子,还有其他的
	//获取轮廓后还可以进一步处理得到更清晰的图像;
	Mat kernel_l = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0);
	Mat ml;
	filter2D(src, ml, -1, kernel_l, Point(-1, -1));
	imshow("laplace image", ml);

	//自定义卷积核
	int c = 0;
	int index = 0;
	int ksize = 3;
	Mat dd;
	while (true)
	{
   
		c = waitKey(500); //每隔500ms模糊一次;
		if ((char)c == 27) //ESC
		{
   
			break;
		}
		ksize = 4 + (index % 8) * 2 + 1 ;
		Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize * ksize); //得到一个ksize 
		filter2D(src, dd, -1, kernel, Point(-1, -1));
		index++;
		imshow("Custom Blur Filter Result", dd);
	}
	waitKey(0);
	return 0;
}

Consequence

效果图: