单片机RGB五彩灯笔记

一、HSV 和 RGB 使用

1,概念:

      HSV:空间颜色,这个模型中颜色的参数分别是:色调(H),饱和度(S),明度(V)。

      RGB:光的三基色  R:红色    G:绿色     B:蓝色

2,RGB和HSV 之间联系

(1)每一种颜色可以用 RGB或则HSV来表示,RGB和HSV之间可以相互转换,HSV常用于色彩的搭配,用途更广。

(2)空间立体图

 

   

3,HSV和RGB相互转化

话不多说直接上代码

(1)RGB转HSV

static int rgb2hsv_max(int a,int b,int c)
{
	int max = a;

	if(b > max) max = b;

	if(c > max) max = c;

	return max;
}

 
static int rgb2hsv_min(int a,int b,int c)
{
	int min = a;

	if(b < min) min = b;

	if(c < min) min = c;

	return min;
}

int rgb2hsv(int r,int g,int b,int *h,int *s,int *v)
{
	int imax,imin,diff;
    int d_r=r*100/255;
	int d_g=g*100/255;
	int d_b=b*100/255;
	imax = rgb2hsv_max(d_r,d_g,d_b);
	imin = rgb2hsv_min(d_r,d_g,d_b);

	diff = imax - imin;

	*v = imax;
	if(imax == 0)
		*s = 0;

	else

		*s = diff;


	if(diff != 0)

	{

		if(d_r == imax)

		{

			*h = 60 * (d_g - d_b) / diff;

		}

		else if(d_g == imax)

		{

			*h = 60 * (d_b - d_r) / diff + 120;

		}

		else

		{

			*h = 60 * (d_r - d_g) / diff + 240;

		}

		if(*h < 0)

			*h = *h + 360;

	}

	else

		*h = -1;


	return 0;

}

(2)HSV转RGB

void hsv2rgb(unsigned char *r, unsigned char *g, unsigned char *b, int h, int s, int v)
{
    int i;
    float RGB_min, RGB_max;
    RGB_max = v*2.55f;
    RGB_min = RGB_max*(100 - s)/ 100.0f;

    i = h / 60;
    int difs = h % 60; // factorial part of h

    // RGB adjustment amount by hue
    float RGB_Adj = (RGB_max - RGB_min)*difs / 60.0f;

    switch (i)
    {
        case 0:
            *r = RGB_max;
            *g = RGB_min + RGB_Adj;
            *b = RGB_min;
            break;
        case 1:
            *r = RGB_max - RGB_Adj;
            *g = RGB_max;
            *b = RGB_min;
            break;
        case 2:
            *r = RGB_min;
            *g = RGB_max;
            *b = RGB_min + RGB_Adj;
            break;
        case 3:
            *r = RGB_min;
            *g = RGB_max - RGB_Adj;
            *b = RGB_max;
            break;
        case 4:
            *r = RGB_min + RGB_Adj;
            *g = RGB_min;
            *b = RGB_max;
            break;
        default:		// case 5:
            *r = RGB_max;
            *g = RGB_min;
            *b = RGB_max - RGB_Adj;
            break;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值