矩阵的掩码操作很简单。其思想是:根据掩码矩阵(也称作核)重新计算图像中每个像素的值。掩码矩阵中的值表示近邻像素值(包括该像素自身的值)对新像素值有多大影响。从数学观点看,我们用自己设置的权值,对像素邻域内的值做了个加权平均。
实现掩码操作的两种方法
void Sharpen(const Mat& myImage,Mat& Result){ CV_Assert(myImage.depth()== CV_8U); // 仅接受uchar图像 Result.create(myImage.size(),myImage.type()); const intnChannels = myImage.channels(); for(int j =1 ; j < myImage.rows-1; ++j) { constuchar* previous = myImage.ptr<uchar>(j - 1); constuchar* current =myImage.ptr<uchar>(j ); constuchar* next =myImage.ptr<uchar>(j + 1); uchar*output = Result.ptr<uchar>(j); for(inti= nChannels;i < nChannels*(myImage.cols-1); ++i) { *output++ = saturate_cast<uchar>(5*current[i] -current[i-nChannels]- current[i+nChannels] - previous[i] - next[i]); } } 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)); }
刚进入函数的时候,我们要确保输入图像是无符号字符类型的。为了做到这点,我们使用了 CV_Assert函数。若该函数括号内的表达式为false,则会抛出一个错误。
CV_Assert(myImage.depth() == CV_8U); // 仅接受uchar图像
然后,我们创建了一个与输入有着相同大小和类型的输出图像。在 图像矩阵是如何存储在内存之中的? 一节可以看到,根据图像的通道数,我们有一个或多个子列。我们用指针在每一个通道上迭代,因此通道数就决定了需计算的元素总数。
Result.create(myImage.size(),myImage.type()); const int nChannels = myImage.channels();
利用C语言的[]操作符,我们能简单明了地访问像素。因为要同时访问多行像素,所以我们获取了其中每一行像素的指针(分别是前一行、当前行和下一行)。此外,我们还需要一个指向计算结果存储位置的指针。有了这些指针后,我们使用[]操作符,就能轻松访问到目标元素。为了让输出指针向前移动,我们在每一次操作之后对输出指针进行了递增(移动一个字节):
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]); } }
在图像的边界上,上面给出的公式会访问不存在的像素位置(比如(0,-1))。因此我们的公式对边界点来说是未定义的。一种简单的解决方法,是不对这些边界点使用掩码,而直接把它们设为0:
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)); // 右边界
filter2D函数
C++: void filter2D(InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor=Point(-1,-1), double delta=0, int borderType=BORDER_DEFAULT )
功能:把输入图像src与核kernel做卷积,结果存放在dst中。
Parameters: |
|
Mat kern = (Mat_<char>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); filter2D(I, K, I.depth(), kern );