灰度是一种图像亮度的表示方法,通过下式计算: $$ Y = 0.2126\ R + 0.7152\ G + 0.0722\ B $$
Mat BGR2GRY(Mat img)
{
int width = img.cols;
int height = img.rows;
Mat out = Mat::zeros(height,width,CV_8UC1);
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
out.at<uchar>(h, w) = 0.2126 * (float)img.at<cv::Vec3b>(h, w)[2] \
+ 0.7152 * (float)img.at<cv::Vec3b>(h, w)[1] \
+ 0.0722 * (float)img.at<cv::Vec3b>(h, w)[0];
}
}
return out;
}
Mat img = cv::imread("D:/chat.png", cv::IMREAD_COLOR);
Mat out = BGR2GRY(img);
imshow("old", img);
imshow("new", out);