二 opencv核心模块
3 对矩阵进行蒙版运算
3.1 我们根据蒙版矩阵(也称为内核)重新计算图像中每个像素的值
3.2 filter2D()函数
应用此类滤镜在图像处理中非常普遍,以至于OpenCV中有一个函数将负责应用遮罩(在某些地方也称为内核)。为此,您首先需要定义一个包含掩码的对象:
Mat kernel = (Mat_<char>(3,3) << 0, -1, 0,
-1, 5, -1,
0, -1, 0);
然后调用filter2D()函数,指定输入,输出图像和要使用的内核
filter2D( src, dst1, src.depth(), kernel );
3.3 基础访问像素方法
函数
void Sharpen(const Mat& myImage,Mat& Result)
{
CV_Assert(myImage.depth() == CV_8U); // accept only uchar images
const int nChannels = myImage.channels();
Result.create(myImage.size(),myImage.type());
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]);
}
}
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 :: CV_Assert函数,当其中的表达式为false时将引发错误。
CV_Assert(myImage.depth()== CV_8U); //只接受uchar图片
我们创建与输入具有相同大小和类型的输出图像。如您在存储部分中所见,根据通道的数量,我们可能会有一个或多个子列。
我们将通过指针遍历它们,因此元素的总数取决于此数目
const int nChannels = myImage.channels();
Result.create(myImage.size(),myImage.type());
我们将使用普通的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]);
}
}
图像边界上可能不存在像素位置(如-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));