掩膜操作
文中用到的掩膜:
[0, -1, 0,
-1, 5, -1,
0, -1, 0]
该掩膜同一颜色区域内不会改变颜色值,但是可以使亮色更亮,暗色更暗,加强对比度(突出颜色边界)
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
//读取图片并进行数据验证
Mat input = imread("E:/Image/yg.jpg");
if (!input.data || input.empty())
{
printf("load image has error!\n");
return 0;
}
namedWindow("input image", 1);
imshow("input image", input);
//手动掩膜操作(未对图片边缘像素进行处理,图片边缘会有一条黑边)
double t1 = getTickCount();//记录时间
Mat out1 = Mat::zeros(input.size(), input.type());//初始化图片
int chans = input.channels();//通道数
int cols = input.cols * chans;//列数*通道数
int rows = input.rows;//行数
for (int row = 1; row < rows - 1; row++)
{
const uchar* prev = input.ptr<uchar>(row - 1);//前一行指针
const uchar* current = input.ptr<uchar>(row);//当前行指针
const uchar* next = input.ptr<uchar>(row + 1);//下一行指针
uchar* out_row = out1.ptr<uchar>(row);//输出图片行
for (int col = chans; col < cols - chans; col++)
{
//saturate_cast:设置数据在某一范围内,uchar:[0,255];
out_row[col] = saturate_cast<uchar>(5 * current[col] - (prev[col] + next[col] + current[col - chans] + current[col + chans]));
}
}
double time1 = (getTickCount() - t1) / getTickFrequency();
printf("time1: %.4lf\n", time1);//输出double类型数据
namedWindow("out1 image", WINDOW_AUTOSIZE);
imshow("out1 image", out1);
//API掩膜操作
double t2 = getTickCount();
Mat out2 = Mat::zeros(input.size(), input.type());
Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);//该掩膜可增强图片对比度
filter2D(input, out2, input.depth(), kernel);
double time2 = (getTickCount() - t2) / getTickFrequency();
printf("time2: %.4f\n", time2);
namedWindow("out2 image", 1);
imshow("out2 image", out2);
waitKey(0);
return 0;
//std::cout << "Hello World!\n";
}