From d9bdb33bc0c4f25ad7b91df7f27d323bf3f77465 Mon Sep 17 00:00:00 2001 From: Sam Hocevar Date: Fri, 11 Jan 2013 13:15:19 +0000 Subject: [PATCH] color: a reasonably fast RGB to HSV conversion with only three tests. --- src/lol/image/color.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/lol/image/color.h b/src/lol/image/color.h index f688f157..95b11c98 100644 --- a/src/lol/image/color.h +++ b/src/lol/image/color.h @@ -79,6 +79,33 @@ public: return vec4(HSVToRGB(src.rgb), src.a); } + /* + * Convert RGB to HSV + */ + static vec3 RGBToHSV(vec3 src) + { + float offset = 0.f; + + if (src.r < src.g) + src = src.grb, offset = -2.f / 6.f; + + if (src.g < src.b) + src = src.rbg, offset = -1.f - 4.f * offset; + + if (src.r < src.g) + src = src.grb, offset = -2.f / 6.f - offset; + + float chroma = src.r - src.b; + return vec3(abs((src.g - src.b) / (6.f * chroma + 1e-40f) + offset), + chroma / (src.r + 1e-40f), + src.r); + } + + static vec4 RGBToHSV(vec4 src) + { + return vec4(RGBToHSV(src.rgb), src.a); + } + /* * Convert linear HSV to linear HSL */