RGB转灰度图主要是通过各颜色分量取适当权重求和实现的,比例有很多种,比例不合适往往会出现某种颜色分量的细节无法显示的情况,恰当比例的灰度图很逼真。
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
cv::Mat BGR2GRAY(cv::Mat img) {
int width = img.cols;
int height = img.rows;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);//8位无符号灰度图像
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//RGB分量取不同的权重
out.at<uchar>(y, x) = 0.2126 *img.at<cv::Vec3b>(y, x)[2] \
+ 0.7152 * img.at<cv::Vec3b>(y, x)[1] \
+ 0.0722 * img.at<cv::Vec3b>(y, x)[0];
}
}
return out;
}
cv::Mat BGR2GRAY2(cv::Mat img) {
int width = img.cols;
int height = img.rows;
cv::Mat out = cv::Mat::zeros(height, width, CV_8UC1);//8位无符号灰度图像
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
//RGB分量取不同的权重
out.at<uchar>(y, x) = 1 *(float)img.at<cv::Vec3b>(y, x)[2] \
+ 0 *(float)img.at<cv::Vec3b>(y, x)[1] \
+ 0 * (float)img.at<cv::Vec3b>(y, x)[0];
}
}
return out;
}
int main(int argc, const char* argv[]) {
cv::Mat img = cv::imread("C:/Users/zxdn/Desktop/boy.jpg", cv::IMREAD_COLOR);
cv::Mat out = BGR2GRAY(img);
cv::Mat out2 = BGR2GRAY2(img);
cv::imshow("各分量合适比例下", out);
cv::imshow("只保留一个颜色分量", out2);
cv::waitKey(0);
cv::destroyAllWindows();
return 0;
}