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; //飽和度
}