opencv RGB转灰度图

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;
}

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值