概述
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);
}
最后
以上就是酷炫彩虹为你收集整理的HSV to RGB and RGB to HSV的全部内容,希望文章能够帮你解决HSV to RGB and RGB to HSV所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复