关于邻域的概念,请查阅有关数字图像处理的书籍,在这里就不再赘述。在图像处理中,利用像素邻域的值来计算本邻域的值是非常常见的事情。例如滤波,边缘检测等。要同时访问多行中像素中的值。
我们选取锐化图像来讲述本节。拉普拉斯算子,关于这个后面的章节会提到。他是一个计算梯度的算子,通常用在边缘检测中。根据拉普拉斯算子模板卷积之后的算式为:sharpened_pixel=5*current-left-right-up-down;left就是本行左边的像素,上就是本列的上一个像素,以此类推。
下面就提出了一个问题,我们的图像还能不能in-place处理。答案当然是否定的。因为我们同时需要三个指针,指向当前行,上一行和下一行。这三个指针指向的像素在处理时都是不可以变化的。于是锐化处理的算法可以这样写:
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
void sharpen(cv::Mat &image, cv::Mat &result)
{
result.create(image.size(),image.type());
//the first ,last row and colum do not process , bucause they do not have up or left neighbour
for(int i = 1; i<image.rows-1; i++)
{
const uchar* previous = image.ptr<const uchar>(i-1);
const uchar* current = image.ptr<const uchar>(i);
const uchar* next = image.ptr<const uchar>(i+1);
uchar* output = result.ptr<uchar>(i);
for (int j=1; j<image.cols-1 ;j++ )
*output++ = cv::saturate_cast<uchar>(5*current[j]-current[j-1]-current[j+1]-previous[j]-next[j]);
}
//Set the unprocess pixels to 0
result.row(0).setTo(cv::Scalar(0));
result.row(result.rows-1).setTo(cv::Scalar(0));
result.col(0).setTo(cv::Scalar(0));
result.col(result.cols-1).setTo(cv::Scalar(0));
}
int _tmain(int argc, _TCHAR* argv[])
{
/*
imread the second parameter:
CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as is (including the alpha chann