If you are given red, green, and blue values that range from 0-255, what would be the fastest computation to get just the hue value? This formula will be used on every pixel of a 640x480 image at 30fps (9.2 million times a second) so every little bit of speed optimization helps.
I've seen other formulas but I'm not happy with how many steps they involve. I'm looking for an actual formula, not a built in library function.
You must specify which language you need. C#, Java and C are very different languages and may runs on different platforms
640x480 is not very large compared to current common resolutions. You must try all the possible solutions and benchmark. An algorithm that has many steps doesn't necessarily slower than a shorter one because instruction cycle are not fixed and there are many other factors that affect performance such as cache coherency.
For the algorithm Umriyaev mentioned above, you can replace the division by 255 with a multiplication by
1.0/255
, that'll improve performance with a bit acceptable error.In C you can do vectorize it to improve it even more. You can also use hardware acceleration.
In C# and Java you don't have many options. You can run unsafe code in C#, or if you're using Mono you can use the vector type that has already support for SSE. In Java you can run native code through JNI
Convert the RGB values to the range 0-1, this can be done by dividing the value by 255 for 8-bit color depth (r,g,b - are given values):
Find the minimum and maximum values of R, G and B.
If Red is max, then Hue = (G-B)/(max-min) If Green is max, then Hue = 2.0 + (B-R)/(max-min) If Blue is max, then Hue = 4.0 + (R-G)/(max-min)
The Hue value you get needs to be multiplied by 60 to convert it to degrees on the color circle. If Hue becomes negative you need to add 360 to, because a circle has 360 degrees.
Here is full article.
In addition to Umriyaev's answer:
If only the hue is needed, it is not required to divide the 0-255 ranged colours with 255.
The result of e.x.
(green - blue) / (max - min)
will be the same for any range (as long as the colours are in the same range of course).Here is the java example to get the Hue:
Edit: added check if min and max are the same, since the rest of the calculation is not needed in this case, and to avoid division by 0 (see comments)