03-矩阵的掩膜操作
代码实现:
//利用掩膜计算提高图像对比度
#include<iostream>
#include<opencv2/opencv.hpp>
#include<math.h>
using namespace std;
using namespace cv;
int main(int argc,char** argv)
{
Mat
myImage, outputImage;
myImage = imread("222.jpg", 1);
if (!myImage.data)
{
cout << "coun't load this image..." << endl;
return -1;
}
namedWindow("input", WINDOW_NORMAL);
imshow("input", myImage);
outputImage = Mat(myImage.size(), myImage.type()); //outputImage初始化,使其尺寸和类型与myImage一样
//myImage.copyTo(outputImage); //复制图片
int nchannels = myImage.channels(); //图片通道
int height = myImage.rows; //矩阵行数
int width = myImage.cols; //列数
//掩膜(MASK)计算
for (int row = 1; row < height - 1; row++)
{
//用指针获取图像像素
const uchar* previous = myImage.ptr<uchar>(row - 1);
const uchar* courrent = myImage.ptr<uchar>(row);
const uchar* next = myImage.ptr<uchar>(row + 1);
uchar* output = outputImage.ptr<uchar>(row);
for (int col = nchannels; col < nchannels*(myImage.cols - 1); col++) //注意乘以通道数
{
*output =saturate_cast<uchar>( 5 * courrent[col] - previous[col] - next[col] -courrent[col - nchannels] - courrent[col + nchannels]);
//saturate_cast<uchar>() 调整像素值,>255返回0,<0返回
output++;
}
}
//上面的计算等价于
//Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); //定义掩膜
//filter2D(myImage, outputImage, myImage.depth(), kernel);
namedWindow("output", WINDOW_NORMAL);
imshow("output", outputImage);
waitKey(0); //无限等待
return 0;
}
没加saturate_cast() 调整像素值时图片如下:存在超限点
备注:以上内容转载笔者早期OneNote笔记,较多为图片格式,比较简陋。
后记:笔者才疏学浅,如有错误,望指出。