#include"opencv2/core/core.hpp"
#include"opencv2/imgproc/imgproc.hpp"
#include
usingnamespacecv;
usingnamespacestd;
//自定义核函数方法,推荐使用此方法,当图像较大时,其执行效率更高
voidsharpen2D_1(Mat&src,Mat&output)
{
Matkernel(3,3,CV_32F,Scalar(0));
kernel.at<float>(1,1)=5.0f;
kernel.at<float>(0,1)=-1.0f;
kernel.at<float>(2,1)=-1.0f;
kernel.at<float>(0,1)=-1.0f;
kernel.at<float>(1,2)=-1.0f;
filter2D(src,output,src.depth(),kernel);
}
//使用指针的方法
voidsharpen2D_2(Mat&src,Mat&output)
{
output.create(src.size(),src.type());
for(intj= 1;j<src.rows-1;j++) {
constuchar*previous=
src.ptr<constuchar>(j-1);
constuchar*current=
src.ptr<constuchar>(j);
constuchar*next=
src.ptr<constuchar>(j+1);
uchar*output_ptr=output.ptr<uchar>(j);
for(inti=1;i<src.cols-1;i++) {
//使用cv::saturate_cast对处理后的像素数据进行转换,可以保证计算后的灰度值在0~255之间 。
*output_ptr++=cv::saturate_cast<uchar>(
5*current[i]-current[i-1]
-current[i+1]-previous[i]-next[i]);
}
}
//图像边缘像素设置为黑色
output.row(0).setTo(Scalar(0));
output.row(output.rows-1).setTo(Scalar(0));
output.col(0).setTo(Scalar(0));
output.col(output.cols-1).setTo(Scalar(0));
}
int_tmain(intargc,_TCHAR*argv[])
{
Matsrc1=imread("D:\\1.jpg",IMREAD_GRAYSCALE);//加载的图像为灰度图
if(!src1.data)
{
cout<<"Image loading failed"<<endl;
}
Matsrc2;
src1.copyTo(src2);
sharpen2D_1(src1,src1);
sharpen2D_2(src2,src2);
namedWindow("sharpen2D_1",WINDOW_AUTOSIZE);
namedWindow("sharpen2D_2",WINDOW_AUTOSIZE);
imshow("sharpen2D_1",src1);
imshow("sharpen2D_2",src2);
waitKey(0);
return0;
}