矩阵的掩模是根据掩模来重新计算每个像素的像素值,掩模(mask)也被称为kernel,通过掩模操作实现的图像对比度调整。掩模操作的原理:
红色是中心像素,从上到下,从左到右对每个像素做同样的处理操作,得到最终结果就是对比度提高之后的输出图像Mat对象,计算公式:I(i,j)==5*I(i,j)-[I(i-1,j)+(i+1,j)+(i,j-1)+(i,j+1)]
掩模的操作还可以调用filter2D函数,具体方法如下:
1.定义掩膜:Mat kernel = (Mat_(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
2.filter2D( src, dst, src.depth(), kernel );其中src与dst是Mat类型变量、src.depth表示位图深度,有32、24、8等
本文代码实现的主要函数有:
(1).获取图像像素指针
Mat.ptr(int i=0) 获取像素矩阵的指针,索引i表示第几行,从0开始计行数。
获得当前行指针const uchar* current= myImage.ptr(row );
获取当前像素点P(row, col)的像素值 p(row, col) =current[col]
(2).像素范围处理saturate_cast<uchar>
,这个函数的功能是确保RGB值的范围在0~255之间:
saturate_cast<uchar>(-100),返回 0。
saturate_cast<uchar>(288),返回25
saturate_cast<uchar>(100),返回100
代码如下:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
int main(int argc, char** argv) {
Mat src, dst;
src = imread("E:/9.JPG");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
namedWindow("input image");
imshow("input image", src);
/*int cols = (src.cols-1) * src.channels();
int offsetx = src.channels();
int rows = src.rows;
//初始化输出图像,zeros使输出图像的大小,类型与输入的图像一致
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]));
}
}
*/
double t = getTickCount();//执行时间
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
filter2D(src, dst, src.depth(), kernel);
double timeconsume = (getTickCount() - t) / getTickFrequency();
printf("tim consume %.2f\n", timeconsume);
namedWindow("OUTPUT");
imshow("OUTPUT", dst);
waitKey(0);
return 0;
}