矩阵的淹没操作即,根据掩膜重新计算图像每个像素的像素值,使图像模糊或锐化。
例:通过掩膜操作使图像对比度提高。
假设当前像素点位置(i,j),当前像素点像素值为I(i,j)。
则I ( i , j ) = 5 * I ( i , j ) - [ I ( i - 1 , j ) + I ( i + 1 , j ) + I ( i , j - 1 ) + I ( i , j + 1 ) ]
即使用如下矩阵( 1 )与以当前像素点为(1,1)的3*3矩阵的计算结果。
(1)
[
0
−
1
0
−
1
5
−
1
0
−
1
0
]
\begin{bmatrix} 0 & -1 & 0\\ -1 & 5 & -1 \\ 0 & -1 & 0 \end{bmatrix} \tag{1}
⎣⎡0−10−15−10−10⎦⎤(1)
功能实现一
Mat src, dst;
//显示原图
src = imread("ysjx.jpg");
if (src.empty()) {
cout << "no image!" << endl;
return -1;
}
namedWindow("opencv", CV_WINDOW_AUTOSIZE);
imshow("opencv", src);
//获取原图信息
int cols = src.cols*src.channels();
int offsetx = src.channels();
int rows = src.rows;
//计算图像新的像素值,显示提高对比度后的图像
dst = Mat::zeros(src.size(), src.type());
for (int row = 1; row < (rows - 1); row++) {
const uchar* previous = src.ptr<uchar>(row - 1);
const uchar* current = src.ptr<uchar>(row);
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]));
}
}
namedWindow("contract image demo1", CV_WINDOW_AUTOSIZE);
imshow("contract image demo1", dst);
运行结果
功能实现二
//显示原图
Mat src, dst;
src = imread("ysjx.jpg");
if (src.empty()) {
cout << "no image!" << endl;
int a;
cin >> a;
return -1;
}
namedWindow("opencv", CV_WINDOW_AUTOSIZE);
imshow("opencv", src);
//计算图像新的像素值,显示提高对比度后的图像
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(src, dst, src.depth(), kernel);//src.depth()表示位图深度
namedWindow("contract image demo2", CV_WINDOW_AUTOSIZE);
imshow("contract image demo2", dst);
运行结果
常用矩阵模板:http://blog.sina.com.cn/s/blog_6ac784290101e47s.html
参考:https://www.bilibili.com/video/av29600072?from=search&seid=10536318364153117214