灰度化
处理三个通道的数据比较复杂,我们先将图像进行灰度化处理,灰度化的过程就是将每个像素点的RGB值统一成同一个值。灰度化后的图像将由三通道变为单通道,单通道的数据处理起来就会简单许多。
通常这个值是根据RGB三通道的数值进行加权计算得到。人眼对RGB颜色的敏感度不同,对绿色最敏感,权值较高,对蓝色最不敏感,权值较低。坐标为(x,y)的像素点进行灰度化操作的具体计算公式如下:
Y = 0.2126 R + 0.7152 G + 0.0722 B Y = 0.2126\ R + 0.7152\ G + 0.0722\ B Y=0.2126 R+0.7152 G+0.0722 B
代码实现
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include<iostream>
using namespace cv;
//灰度化
Mat BGR2GRAY(Mat img)
{
//获取图像宽高
int height = img.rows;
int width = img.cols;
//输出图像画布
Mat out = Mat::zeros(height,width, CV_8UC1);
//遍历图像
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// BGR -> Gray uchar 是单通道;vec3b是三通道
out.at<uchar>(y, x) = 0.2126 * (float)img.at<Vec3b>(y, x)[2] + 0.7152 * (float)img.at<Vec3b>(y, x)[1] + 0.0722 * (float)img.at<Vec3b>(y, x)[0];
}
}
return out;
}
int main()
{
Mat img = imread("lena.jpg");
imshow("origin", img);
Mat out = BGR2GRAY(img);
imshow("sample", out);
waitKey(0);
return 0;
}
结果显示
原图
结果