目录
配置
关于配置vs2019 的opencv 环境,可以参考这篇博文,传送门。
原理知识
关于图像做卷积的原理知识,因为知识很基本就不写了,可以参考这篇博文,传送门
卷积核
底层代码
#include<opencv2\opencv.hpp>
#include<highgui.h>
#include<iostream>
#include<math.h>
using namespace cv;
int main(int argc, char** argv)
{
Mat gray,dst;
Mat src = imread("22.jpg");//读取图像
namedWindow("Window Title", WINDOW_NORMAL);//打开窗口,参数一是窗口名子
if (src.empty())
{
printf("picture is wrong");
}
else
{
imshow("Window Title", src);//显示图像
int cols = (src.cols - 1) * src.channels();//获取图像的列
int offsetx = src.channels();//图像通道数
int rows = src.rows;//获取图像的行
dst = Mat::zeros(src.size(),src.type());//生成和原图相等大小的空矩阵
//遍历图像像素
for (int row = 1; row<(rows-1); row++)
{
const uchar* previous = src.ptr<uchar>(row - 1);//获取上一行指针
const uchar* current = src.ptr<uchar>(row);//获取当前行指针
const uchar* next = src.ptr<uchar>(row + 1);//获取下一行指针
uchar* ouput = dst.ptr<uchar>(row);
for (int col = offsetx; col < cols; col++)//遍历每一行中像素
{
ouput[col] = saturate_cast<uchar>(5*current[col]-(current[col-offsetx]+current[col+offsetx]+previous[col]+next[col]));//执行滤波运算
}
}
namedWindow("outout window",WINDOW_AUTOSIZE);
imshow("outout window", dst);
}
/*imwrite("21.png",gray);*/
waitKey(0);
return 0;
}
使用封装的代码
#include<opencv2\opencv.hpp>
#include<highgui.h>
#include<iostream>
#include<math.h>
using namespace cv;
int main(int argc, char** argv)
{
Mat gray,dst;
Mat src = imread("22.jpg");//读取图像
namedWindow("Window Title", WINDOW_NORMAL);//打开窗口,参数一是窗口名子
if (src.empty())
{
printf("picture is wrong");
}
else
{
imshow("Window Title", src);//显示图像
namedWindow("outout window",WINDOW_AUTOSIZE);
double t = getTickCount();//获取时间
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); //定义滤波器大小
filter2D(src,dst,src.depth(),kernel);//进行卷积操作
double timeconsume = (getTickCount()-t)/getTickFrequency();//计算时间
printf("time consume %3.f\n",timeconsume);
imshow("outout window", dst);
}
/*imwrite("21.png",gray);*/
waitKey(0);
return 0;
}
如有帮组,请点赞,谢谢。