本文是对OpenCV2.4.13文档的部分翻译,作个人学习之用,并不完整。
掩码操作的核心思想就是根据掩码矩阵(kernel)重计算图像中的每个值。掩码矩阵中的值会隐含对邻近像素由多大影响。从数学角度看就是使用我们指定的值来做加权平均值。
基本方法:
void Sharpen(const Mat& myImage, Mat& Result)
{
CV_Assert(myImage.depth() == CV_8U); //只接受char类型图像
Result.create(myImage.size(), myImage.type());//创建与输入图像相同类型和大小的输出图像
const int nChannels = myImage.channels();
for(int j = 1; j < myImage.rows - 1; ++j)
{
const uchar* previous = myImage.ptr<uchar>(j - 1);
const uchar* current = myImage.ptr<uchar>(j );
const uchar* next = myImage.ptr<uchar>(j + 1);//需要三个指针同时访问三行
uchar* output = Result.ptr<uchar>(j);
for(int i = nChannels; i < nChannels * (myImage.cols - 1); ++i)
{
*output++ = saturate_cast<uchar>(5 * current[i]-current[i - nChannels] - current[i + nChannels] - previous[i] - next[i]);//用[]直接访问,每次操作后通过移动指针往后1字节
}
}
Result.row(0).setTo(Scalar(0));
Result.row(Result.rows - 1).setTo(Scalar(0));
Result.col(0).setTo(Scalar(0));
Result.col(Result.cols - 1).setTo(Scalar(0));//图像边缘不采用掩码,可以直接设置值
}
直接应用掩码矩阵
Mat kern=(Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
filter2D(I,K,I.depth(),kern);//指定输入、输出和掩码矩阵,可以有第五个参数来制定掩码矩阵的中心,第六个参数决定在区域内要做什么