Is there a way to convert HSV color arguments to RGB type color arguments using pygame modules in python? I tried the following code, but it returns ridiculous values.
import colorsys
test_color = colorsys.hsv_to_rgb(359, 100, 100)
print(test_color)
and this code returns the following nonsense
(100, -9900.0, -9900.0)
This obviously isn't RGB. What am I doing wrong?
That function expects decimal for
s
(saturation) andv
(value), not percent. Divide by 100.If you would like the non-normalized RGB tuple, here is a function to wrap the
colorsys
function.Example functionality
If you are working with Numpy arrays then
matplotlib.colors.hsv_to_rgb
is quite direct:Note that the input and output images have values in the range [0, 1].
The Hue argument should also vary from 0-1.
I found the following code to work with images represented as numpy ndarrays:
The last division was useful to convert to a floating representation between 0.0 and 1.0, as for some reason the last component originally ranged between 0 and 255.
If you like performance, it's best to avoid imports and use your own optimized code
Here's the exact code from colorsys slightly modified to make the byte-code slightly faster:
output:
Using an if-chain like above is actually faster than using elif
Using a wrapper, like in Cyber's answer, takes a few extra steps for the interpreter to perform.
To add, the for loop in Cyber's example is a real performance killer when used like that
If you want slightly more performance, simply do this:
(I won't say this is the best possible performance, but it's certainly better)
^ this guarantees int() output with a range of 255 (the input is still the same)
TIP: stay away from 3rd-party where possible, try the direct approach if you can.
exculusions: compiled C extensions such as PIL or NumPy, or ctypes wrappers such as PyOpenGL (uses the DLL)
I have prepared a vectorized version, it is cca 10x faster