掩膜操作可以实现图像对比度的调整,使得图像可以锐化,提高图像对比度。
公式为:I(i,j)=5*I(i,j)-[I(i-1,j)+I(i+1,j)+I(i,j-1)+I(i,j+1)] 其中i为行j为列
Mat.ptr<uchar>(int i=0)获取像素矩阵的指针,索引i表示第几行,从0开始。
方法一
自己编写掩膜
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
int main(int argc, char** argv)
{
Mat src,dst;
src=imread("E:/c++/8-13OPENCV/Study 1/2.jpg");
if (src.empty())
{
printf("无");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
int cols = (src.cols - 1) * src.channels();//
int offsetx = src.channels(); //通道数量
int rows = src.rows;
Mat dst = Mat(src.size(), src.type());
for (int row = 1; row < (rows - 1); row++)
{
const uchar* current = src.ptr<uchar>(row); //当前行
const uchar* previous = src.ptr<uchar>(row - 1);
const uchar* next = src.ptr<uchar>(row + 1);
uchar* output = dst.ptr<uchar>(row);
for(int col = offsetx; col < cols; col++)
{
output[col] = saturate_cast<uchar>(5 * current[col] - (current[col - offsetx] + current[col + offsetx] + previous[col] + next[col]));
}
}
waitKey(0);
return 0;
}
//uchar* output = dst.ptr<uchar>(row);定义一个uchar类型指针指向当前行,行数从0开始, output[col] 即代表像素值p(row,col),然后用像素范围处理函数处理
//像素范围处理函数 saturate_cast<uchar> 确保RGB值范围在0~255之间。如果i<=0,返回0;如果i>=255,返回255;如果i在0~255之间那么就返回当前值。
方法二
直接使用filter2D函数(src.depth()可以直接用-1代替,kernel就是矩阵的掩膜。)
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
int main(int argc, char** argv)
{
Mat src,dst;
src=imread("E:/c++/8-13OPENCV/Study 1/2.jpg");
if (src.empty())
{
printf("无");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); //3*3掩膜
filter2D(src, dst, src.depth(), kernel); // 掩膜的函数 **filter2D
namedWindow("contrast image demo", WINDOW_AUTOSIZE);
imshow("contrast image demo", dst);
waitKey(0);
return 0;
}