vec3 rgb2hsv(vec3 rgb)
{
//返回的 vec3 中, r 表示 h, g 表示 s, b 表示 v,均为归一化的值,包括色相 s。
float h, s, v;
float maxValue = max(rgb.r, max(rgb.g, rgb.b));
float minValue = min(rgb.r, min(rgb.g, rgb.b));
v = maxValue - minValue;
if ( v == 0.0 )
{
s = h = 0.0;
}
else
{
s = v / maxValue;
if (maxValue == rgb.r)
h = ((rgb.g - rgb.b) / v + (rgb.g < rgb.b ? 6.0 : 0.0)) / 6.0;
else if (maxValue == rgb.g)
h = ((rgb.b - rgb.r) / v + 2.0) / 6.0;
else
h = ((rgb.r - rgb.g) / v + 4.0) / 6.0;
}
return vec3(h, s, maxValue);
}
vec3 hsv2rgb(float h, float s, float v)
{
float r, g, b;
if ( s == 0.0 )
{
r = g = b = v;
}
else
{
h *= 6.0;
float f = h - floor(h);
int i = int(h);
float p = v * (1.0 - s);
float q = v * (1.0 - s * f);
float t = v * (1.0 - s * (1.0 - f));
if (0 == i || 6 ==i){
r = v; g = t; b = p;
}
else if( 1 == i){
r = q; g = v; b = p;
}
else if( 2 == i){
r = p; g = v; b = t;
}
else if( 3 == i){
r = p; g = q; b = v;
}
else if( 4 == i){
r = t; g = p; b = v;
}
else if( 5 == i){
r = v; g = p; b = q;
}
}
return vec3(r, g, b);
}
转载请注明:《RGB与HSV互转的GLSL代码》