opencv-015 自定义线性滤波

自定义线性滤波

l卷积概念

l常见算子

l自定义卷积模糊

l代码演示

卷积概念

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

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

卷积如何工作

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

扫描二维码关注公众号,回复: 4393001 查看本文章

Sum = 8x1+6x1+6x1+2x1+8x1+6x1+2x1+2x1+8x1

New pixel = sum / (m*n)

常见算子

Robert算子

Sobel算子

拉普拉斯算子

自定义卷积模糊

 

lfilter2D方法filter2D(

Mat src, //输入图像

Mat dst, // 模糊图像

int depth, // 图像深度32/8

Mat kernel, // 卷积核/模板

Point anchor, // 锚点位置

double delta // 计算出来的像素+delta

)

其中 kernel是可以自定义的卷积核

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;

Mat src, dst, gray_src;

int main(int agrc, char** agrv) {

	src = imread("C:/Users/liyangxian/Desktop/bjl/nm3.jpg");
	if (!src.data) {
		printf("no load..\n");
		return -1;
	}
	const char* input_win = "input";
	const char * out_put = "rober X";
	namedWindow(input_win, CV_WINDOW_AUTOSIZE);
	namedWindow(out_put, CV_WINDOW_AUTOSIZE);
	imshow(input_win, src);
	//Robert X方向
	Mat kernel_x = (Mat_<int>(2, 2) <<1, 0, 0, -1);
	filter2D(src, dst, -1, kernel_x, Point(-1, -1), 0.0);
	//Robert Y方向
	Mat ying;
	Mat kernel_y = (Mat_<int>(2, 2) << 0, 1, -1, 0);
	filter2D(src, ying, -1, kernel_y, Point(-1, -1), 0.0);
	//sobel x方向
	Mat sobx_pic;
	Mat sobel_x= (Mat_<int>(3, 3) << -1,0, 1, -2, 0,2,-1,0,1);
	filter2D(src, sobx_pic, -1, sobel_x, Point(-1, -1), 0.0);
	//sobel y方向
	Mat soby_pic;
	Mat sobel_y = (Mat_<int>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1);
	filter2D(src, soby_pic, -1, sobel_y, Point(-1, -1), 0.0);
	//拉普拉斯算子
	Mat lap_pic;
	Mat kernel_lap = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0);
	filter2D(src, lap_pic, -1, kernel_lap, Point(-1, -1), 0.0);

	//自定义滤波,不断刷新进行模糊。
	int c = 0;
	int index = 0;
	int ksize = 3;
	Mat dst_pic;
	while (true) {
		c = waitKey(500);
		if ((char)c == 27) {//ESC键
			break;
		}
		ksize = 4 + (index % 5) * 2 + 1;
		Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize*ksize);
		filter2D(src, dst_pic, -1, kernel, Point(-1, -1));
		index++;
		imshow("zidingyi", dst_pic);
	}
	imshow(out_put, dst);
	imshow("robert_y", ying);
	imshow("sobel_x", sobx_pic);
	imshow("sobel_y", soby_pic);
	imshow("lap_pic", lap_pic);
	waitKey(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41167777/article/details/84819197