2017年全国大学生电子设计竞赛(预测题)-RGB转HSL

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CSDN_he_01/article/details/76887315

2017年全国大学生电子设计竞赛(预测题)-RGB转HSL

在预测题中有一个板球系统的预测题,与不久前所给出的元器件的清单有很多的吻合之处,故很多人都开始做板球控制系统,我们小组面临的第一个问题就是图像处理这块,现在将成功后的经验分享出来。

 

首先是,参照网上的大部分的成功做法我们也采用腐蚀算法来处理,而首先是图像RGB颜色模式的转成HSL颜色模式的转换问题,虽然网上已有源码,但还是要进行源码分析的。下面进行源码分析,至于RGB和HSL的原理请自行百度。

我们使用就结构体来表示这两种格式的颜色

typedef struct					  //HLS格式
{
	unsigned char Hue;			 //色度,[0,240]				
	unsigned char Lightness;		//亮度,[0,240]	     
	unsigned char Saturation;		//饱和度,[0,240]	     
}COLOR_HLS;
typedef struct 				//RGB格式
{
	unsigned char Red;		// [0,255]
	unsigned char Green;            // [0,255]
	unsigned char Blue;             // [0,255]
}COLOR_RGB;

再来就是RGB和HSL的转换公式


 

 

接下来就是RGB转HSL的函数

/*************************************
//RGB转HLS
//H:色度
//L:亮度
//S:饱和度

*************************************/
static void RGB2HSL( const COLOR_RGB* color_rgb, COLOR_HLS* color_hls )
{
	int r, g, b;
	int h, l, s;
	int max, min, dif;
	
	r = color_rgb->Red;
	g = color_rgb->Green;
	b = color_rgb->Blue;
	
	max = maxOf3Values( r, g, b );//计算RGB三个值中的最大值
	min = minOf3Values( r, g, b );//计算RGB三个值中的最小值
	dif = max - min;
	
	//计算l,亮度
	l = ( max + min ) * 240 / 255 / 2;
	
	//计算H,色度
	if( max == min )
	{
		s = 0;
		h = 0;
	}
	else
	{
		
		if( max == r )
		{
			if( min == b )
			{
				h = 40 * ( g - b ) / dif;
			}
			else if( min == g )
			{
				h = 40 * ( g - b ) / dif + 240;
			}
			
		}
		else if( max == g )
		{
			h = 40 * ( b - r ) / dif + 80;
		}
		else if( max == b )
		{
			h = 40 * ( r - g ) / dif + 160;
		}
		
		//计算S,饱和度
		if( l == 0 )
		{
			s = 0;
		}
		else if( l <= 120 )
		{
			s = dif * 240 / ( max + min );
		}
		else
		{
			s = dif * 240 / ( 480 - ( max + min ) );
		}		 
	}   
    	color_hls->Hue = h;				//色度
	color_hls->Lightness = l;		        //亮度
	color_hls->Saturation = s;			//饱和度
}

猜你喜欢

转载自blog.csdn.net/CSDN_he_01/article/details/76887315