Opencv学习笔记(5)——自定义线性滤波,常见卷积算子,Canny边缘检测
这一章我将为大家介绍Opencv中的自定义线性滤波、图像边缘处理、Sober算子和Laplance算子以及Canny边缘检测的相关应用。
一.自定义线性滤波
1.相关原理
1.卷积概念
- 卷积是图像处理中一个操作,是kernel在图像的每个像素上的操作。
- Kernel本质上一个固定大小的矩阵数组,其中心点称为锚点(anchor point)
2.卷积如何工作
把kernel放到像素数组之上,求锚点周围覆盖的像素乘积之和(包括锚点),用来替换锚点覆盖下像素点值称为卷积处理。数学表达如下:
3.常见算子
Robert算子
Sobel算子
拉普拉斯算子
2.相关API
//filter2D方法
filter2D(
Mat src, //输入图像
Mat dst, // 模糊图像
int depth, // 图像深度32/8
Mat kernel, // 卷积核/模板
Point anchor, // 锚点位置
double delta // 计算出来的像素+delta
)
其中 kernel是可以自定义的卷积核
自定义卷积模糊
3.程序运行
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
Mat src, dst, gray_src;
const char* output_title = "Robert_X";
void Threshold_Demo(int, void*);
int main(int argc, char** argv) {
src = imread("D:/photos/2.jpg");
if (!src.data) {
std::cout << "could not find image...\n";
return -1;
}
namedWindow("input_image", CV_WINDOW_AUTOSIZE);
namedWindow(output_title, CV_WINDOW_AUTOSIZE);
imshow("input_image", src);
//SobelX方向
//Mat kernel_x = (Mat_<int>(3, 3) << -1, 0, 1,-2,0, 2,-1,0,1);//定义Sober卷积算子
//filter2D(src, dst, -1, kernel_x, Point(-1, -1), 0, 0);
//imshow("Robert_X", dst);
//SobelY方向
//Mat ying;
//Mat kernel_y = (Mat_<int>(3, 3) << -1, -2, -1, 0,0,0,1,2,1);
//filter2D(src, ying, -1, kernel_y, Point(-1, -1), 0, 0);
//imshow("Robert_Y", dst);
//拉普拉斯算子
//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);
//imshow("Laplace", dst);
//自定义线性滤波
int c = 0;
int index = 0;
int ksize = 5;
while (true) {
c = waitKey(500);//隔500ms模糊一下
if ((char)c == 27) {
break;//按ESC退出
}
ksize = 4 + (index % 5) * 2 + 1;//不断改变卷积算子的尺寸,动态循环
Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize*ksize);//定义线性滤波算子
filter2D(src, dst, -1, kernel, Point(-1, -1));
index++;
imshow("自定义线性滤波", dst);
}
waitKey(0);
return 0;
}