HSV to RGB and RGB to HSV

Sometimes we need to transform between color spaces in shaders.There 2 ways to transform between HSV and RGB.

The shorter one, which is not compatible on some IOS devices like iPhone6 Plus(may be it's due to the precision of e in rgb2hsv, maybe we can turn it a little bigger like 1.0e-6 in lowp so that it won't turn out to be 0):

vec3 rgb2hsv(vec3 c)
{
    vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
    vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
    vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));

    float d = q.x - min(q.w, q.y);
    float e = 1.0e-10;
    return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}

vec3 hsv2rgb(vec3 c)
{
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}

The longer one, not so beautiful but compatible on most devices, and it can be shorter, you can polish it as you wish:

vec3 hsvtorgb(float h, float s, float v) 
{
	float C = v*s;
	float hh = h * 6.0;
	float X = C*(1.0-abs(mod(hh,2.0)-1.0));
	float r,g,b;
	r = g = b = 0.0;
	if( hh>=0.0 && hh<1.0 )
	{
		r = C;
		g = X;
	}
	else if( hh>=1.0 && hh<2.0 )
	{
		r = X;
		g = C;
	}
	else if( hh>=2.0 && hh<3.0 )
	{
		g = C;
		b = X;
	}
	else if( hh>=3.0 && hh<4.0 )
	{
		g = X;
		b = C;
	}
	else if( hh>=4.0 && hh<5.0 )
	{
		r = X;
		b = C;
	}
	else
	{
		r = C;
		b = X;
	}
	float m = v-C;
	r += m;
	g += m;
	b += m;
	return vec3(r,g,b);
}

vec3 rgbtohsv(float r, float g, float b) 
{
 	float M = max(r,max(g,b));
 	float m = min(r,min(g,b));
 	float C = M-m;
	float h,s,v;
 	if( C==0.0 ) h=0.0;
 	else if( M==r ) h=mod((g-b)/C, 6.0);
 	else if( M==g ) h=(b-r)/C+2.0;
 	else h=(r-g)/C+4.0;
 	h*=60.0;
 	if( h<0.0 ) h+=360.0;
 	v = M;
 	if( v==0.0 )
 		s = 0.0;
 	else
 		s = C/v;
	h /= 360.0;
	return vec3(h,s,v);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值