图像灰度化(C语言实现)

RGB三色图变成【0,255】的灰度图的简单方法

方法1. 取RGB的平均值,即 pixel(i , j) = R(i , j) + G(i , j) + B(i , j) 

方法2. 颜色空间的转换(RGB -> YUV),取Y分量(YUV中的 Y表示亮度)计算公式

pixel(i , j) = 0.3 * R(i , j) + 0.59 * G(i , j) + 0.11 * B(i , j)


#include "JpegDecoder.h"
#include <stdio.h>
#include <opencv2/highgui.hpp>
#include <math.h>

using namespace JpegCodec;

static cv::Mat ConvertToMat(Matrix &mat)
{
	int channel = CV_8UC3;
	if (mat.channal == 1) channel = CV_8UC1;

	cv::Mat img(mat.rows, mat.cols, channel);  // create a new matrix

	for (int i = 0; i < mat.rows * mat.cols * mat.channal; i++)
	{
		img.data[i] = mat.data[i];
	}

	return img;
}


void ShowImage(Matrix &mat)
{
	cv::Mat img = ConvertToMat(mat);
	cv::imshow("Bitmap", img);
}


/* 方法一 */
void Gray(Matrix &dst, Matrix &src)
{
	dst.Create(src.rows, src.cols, 1);

	for (int i = 0; i < src.rows; i++)
	{
		for (int j = 0; j < src.cols; j++)
		{
			int idx = (i * src.rows + j) * 3;
			dst.data[idx / 3] = (src.data[idx] + src.data[idx + 1] + src.data[idx + 2]) / 3;
		}
	}
}

/* 方法二 */
void Gray(Matrix &dst, Matrix &src)
{
	dst.Create(src.rows, src.cols, 1);

	for (int i = 0; i < src.rows; i++)
	{
		for (int j = 0; j < src.cols; j++)
		{
			int idx = (i * src.rows + j) * 3;
			dst.data[idx / 3] = 0.3 * src.data[idx] + 0.59 * src.data[idx + 1] + 0.11 * src.data[idx + 2];
		}
	}
}

int main(int argc, char *arrv[])
{
	JpegDecoder decoder("01.jpg");
	Matrix mat, dst;
	decoder.Decoder(mat);

	Gray(dst, mat);
	ShowImage(dst);

	cvWaitKey(0);
	return 0;
}

JpegDecoder: https://github.com/lzb-cc/JpegCodecs

运行示例

转载于:https://my.oschina.net/tigerBin/blog/1486684

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值