卷积是图像处理中一个操作,是kernel在图像的每个像素上的操作。
Kernel本质上一个固定大小的矩阵数组,其中心点称为锚点(anchor point)
卷积如何工作
把kernel放到像素数组之上,求锚点周围覆盖的像素乘积之和(包括锚点),用来替换锚点覆盖下像素点值称为卷积处理。数学表达如下:
常见算子
robert算子
sobel算子
拉普拉斯算子
定义算子的方式
Mat robertkernelx = (Mat_<int>(2, 2) << 1, 0, 0, -1);
自定义卷积模糊
filter2D方法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;
int main(int argc, char** argv)
{
Mat src, dst1,dst2,dst3,dst4,dst5,dst6;
src = imread("F:/1.jpg");
if(!src.data)
{
cout << "cannot load image" << endl;
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
Mat robertkernelx = (Mat_<int>(2, 2) << 1, 0, 0, -1);
filter2D(src, dst1, -1, robertkernelx, Point(-1, -1), 0, 0);
Mat robertkernely = (Mat_<int>(2, 2) << 0,1,-1,0);
filter2D(src, dst2, -1, robertkernely, Point(-1, -1), 0, 0);
Mat sobelkernelx = (Mat_<int>(3, 3) << -1, 0, 1, -2, 0, 2, -1, 0, 1);
filter2D(src, dst3, -1, sobelkernelx, Point(-1, -1), 0, 0);
Mat sobelkernely = (Mat_<int>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1);
filter2D(src, dst4, -1, sobelkernely, Point(-1, -1), 0, 0);
Mat laplaciankernel = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0);
filter2D(src, dst5, -1, laplaciankernel, Point(-1, -1), 0, 0);
//imshow("output1", dst1);
//imshow("output2", dst2);
//imshow("output3", dst3);
//imshow("output4", dst4);
imshow("output5", dst5);
int ksize = 0;
int c = 0;
int index = 0;
while (true)
{
c = waitKey(500);
if ((char)c == 27)
{
break;
}
ksize = 4 + (index % 8) * 2 + 1;
Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize * ksize);
filter2D(src, dst6, -1, kernel, Point(-1, -1));
index++;
imshow("custom filter", dst6);
}
waitKey(0);
return 0;
}