最近开始研究opencv2,为了便于以后的查阅,决定在博客中记录学习笔记
(1)利用指针对图像进行滤波:
<span style="font-family: Arial, Helvetica, sans-serif;">void sharpen(Mat &img,Mat &dst)</span>
{
dst.create(img.size(),img.type());
if (img.channels()==3)
{
for (int i = 1;i < img.rows-1;i++)
{
Vec3b* pre = img.ptr<Vec3b>(i-1);
Vec3b* cur = img.ptr<Vec3b>(i);
Vec3b* nex = img.ptr<Vec3b>(i+1);
Vec3b* ptr = dst.ptr<Vec3b>(i);
for (int j = 1;j < img.cols-1;j++)
{
ptr[j][0] = saturate_cast<uchar>(5*cur[j][0]-cur[j-1][0]-cur[j+1][0]-pre[j][0]-nex[j][0]);
ptr[j][1] = saturate_cast<uchar>(5*cur[j][1]-cur[j-1][1]-cur[j+1][1]-pre[j][1]-nex[j][1]);
ptr[j][2] = saturate_cast<uchar>(5*cur[j][2]-cur[j-1][2]-cur[j+1][2]-pre[j][0]-nex[j][2]);
}
}
dst.row(0) = img.row(0);
dst.row(dst.rows-1) = img.row(img.rows-1);
dst.col(0) = img.col(0);
dst.col(dst.cols-1) = img.col(img.cols-1);
}
if (img.channels()==1)
{
for (int i = 1;i < img.rows;i++)
{
uchar* graypre = img.ptr<uchar>(i-1);
uchar* graycur = img.ptr<uchar>(i);
uchar* graynex = img.ptr<uchar>(i+1);
uchar* grayptr = dst.ptr<uchar>(i);
for (int j = 1;j < img.cols;j++)
{
grayptr[j] = saturate_cast<uchar>(5*graycur[j]-graycur[j-1]-graycur[j+1]-graypre[j]-graynex[j]);
}
}
dst.row(0) = img.row(0);
dst.row(dst.rows-1) = img.row(img.rows-1);
dst.col(0) = img.col(0);
dst.col(dst.cols-1) = img.col(img.cols-1);
}
}
(2)利用滤波器对图像进行滤波:
void sharpen2D(Mat &img,Mat &dst)
{
Mat kernel(3,3,CV_32F,Scalar(0));
kernel.at<float>(1,1) = 5.0;
kernel.at<float>(0,1) = -1.0;
kernel.at<float>(1,0) = -1.0;
kernel.at<float>(2,1) = -1.0;
kernel.at<float>(1,2) = -1.0;
filter2D(img,dst,img.depth(),kernel);
}