RGB to HSV to RGB – for Shaders

Posted by in Software

TL;DR: Go here to get the RGB->HSV and HSV->RGB conversion functions for shaders.

The other day I tried to tint a colour in a texture (or rather all texture) with a different colour. It’s quite easy to rotate things around, but, if you want to do it parametrically, you’ll need something a bit more complex.


The easiest way (?!?!) I could come up with was to shift the hue off all colors using a RGB<->HSV conversion. The algorithm in a shader would be quite simple:

Simple, right?

Now, the two functions are:

  1. RGB -> HSV:

  2. HSV -> RGB:

Now, all you have to do is place them in a fragment shader and apply the above algorithm.

Vertex shader

The vertex shader is quite basic (done in the OS X’s OpenGL Shader Builder):

Fragment shader

The fragment shader is like this (sand the two above methods for brevity)

Yes, it’s like the one from SO, but with the difference that values for hue are between 0 and 1 (rather than 0-360).

Now, all we have to do is to tint only some of the colours… :)

A little experiment: If you find this post and ad below useful, please check the ad out :-)