OpenCV图像处理:图像锐化操作
操作系统Win10
工具:VS2019、OpenCV4.0.0
核心算法:
saturate_cast(5 * current[j] -
current[j - channels] - current[j + channels] -
previous[j] - next[j])
测试结果:
测试代码
#include <opencv.hpp>
#include
using namespace std;
using namespace cv;
void Sharpen(const Mat& src, Mat& dst)
{
int channels = src.channels();
int rows = src.rows;
int cols = src.cols;
//创建一个与src同类型pixel同大小
dst.create(src.size(), src.type());
//只对第1行到rows-1行进行处理
for (int i = 1; i < rows - 1; ++i)
{
//前一行的指针
//当前行的指针
//后一行的指针
const uchar* previous = src.ptr(i - 1);
const uchar* current = src.ptr(i );
const uchar* next = src.ptr(i + 1); //取得dst第i行的指针
uchar* output = dst.ptr(i);
//只对第1列到cols-1行进行处理
for (int j = channels; j < channels * (cols - 1); ++j)
{
//对dst的第i行锐化处理操作
//saturate_cast像素越界处理
//*** *** ***
//*** *** ***
//*** *** ***
//(1,3)*5-(1,0)-(1,6)-(0,3)-(2,3)
output = saturate_cast(5 * current[j] -
current[j - channels] - current[j + channels] -
previous[j] - next[j]);
//output指针下移处理下一行
output++;
}
}
//还有第1、rows行,第1、cols列未处理,置0
dst.row(0).setTo(Scalar(0));
dst.row(rows - 1).setTo(Scalar(0));
dst.col(0).setTo(Scalar(0));
dst.col(cols-1).setTo(Scalar(0));
}
int main(int argc, char argv[])
{
Mat src_mat = imread(“C:/Users/Cocos/Desktop/1.jpg”);
Mat dst_mat;
if (src_mat.empty())
{
cout << “读取图像失败,程序退出” << endl;
return EXIT_FAILURE;
}
printf(“图像分辨率:%d * %d 类型:%d\n”,
src_mat.rows,
src_mat.cols,
src_mat.type());
cout << “读取图像成功,正在处理…” << endl;
namedWindow(“src_mat”, WINDOW_AUTOSIZE);
imshow(“srt_mat”, src_mat);
//用于查看处理图像所用时间
double t = (double)getTickCount();
Sharpen(src_mat, dst_mat);
t = ((double)getTickCount() - t) / getTickFrequency();
cout << “图像锐化处理成功,共花费:” << t << “s” << endl;
namedWindow(“dst_mat”, WINDOW_AUTOSIZE);
imshow(“dst_mat”, dst_mat);
waitKey(0);
return 0;
}