一、理论
1.卷积概念
- 卷积是图像处理中一个操作,是kernel在图像的每个像素上的操作。
-
Kernel本质上一个固定大小的矩阵数组,其中心点称为锚点(anchor point)
2.卷积如何操作
把kernel放到像素数组之上,求锚点周围覆盖的像素乘积之和(包括锚点),用来替换锚点覆盖下像素点值称为卷积处理。数学表达如下:



二、常见算子
Robert算子

Sobel算子

拉普拉斯算子

三、自定义卷积模糊
filter2D方法
filter2D(
Mat src, //输入图像
Mat dst, // 模糊图像
int depth, // 图像深度32/8
Mat kernel, // 卷积核/模板
Point anchor, // 锚点位置
double delta // 计算出来的像素+delta
)
其中 kernel是可以自定义的卷积核

四、综合例程
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
int ksize = 0;
src = imread("D:/vcprojects/images/test1.png");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
char INPUT_WIN[] = "input image";
char OUTPUT_WIN[] = "Custom Blur Filter Result";
namedWindow(INPUT_WIN, CV_WINDOW_AUTOSIZE);
namedWindow(OUTPUT_WIN, CV_WINDOW_AUTOSIZE);
imshow(INPUT_WIN, src);
// Sobel X 方向
// Mat kernel_x = (Mat_<int>(3, 3) << -1, 0, 1, -2,0,2,-1,0,1);
// filter2D(src, dst, -1, kernel_x, Point(-1, -1), 0.0);
// Sobel Y 方向
// Mat yimg;
// Mat kernel_y = (Mat_<int>(3, 3) << -1, -2, -1, 0,0,0, 1,2,1);
// filter2D(src, yimg, -1, kernel_y, Point(-1, -1), 0.0);
// 拉普拉斯算子
//Mat kernel_y = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0);
//filter2D(src, dst, -1, kernel_y, Point(-1, -1), 0.0);
int c = 0;
int index = 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(OUTPUT_WIN, dst);
}
// imshow("Sobel Y", yimg);
return 0;
}