Python – colorsys.hsv_to_rgb returning a float value
Question:
Why is hsv_to_rgb
returning a float value for this? and only for g and b?
import colorsys
from colorsys import *
colorRGB = (255,0,255)
print(colorRGB)
colorHSV = rgb_to_hsv(colorRGB[0],colorRGB[1],colorRGB[2])
colorRGB = hsv_to_rgb(colorHSV[0],colorHSV[1],colorHSV[2])
print(colorRGB)
(255, 0, 255)
(255, 0.0, 255.0)
[Finished in 0.0s]
Answers:
Solution
You need to rescale RGB values 0 to 255 between 0 to 1 first.
Section Code Modification below gives you a modified version of your code that will run bug-free.
If you try this, you would realize what is happening.
# we provide r, g, b values ranging between 0 and 1 for each.
colorsys.hsv_to_rgb(*colorsys.rgb_to_hsv(1,0,0))
Output:
(1, 0.0, 0.0)
Code Modification
I would change your code as follows (rescale 0-255 between 0-1):
from colorsys import hsv_to_rgb, rgb_to_hsv
colorRGB = (255,0,255)
colorRGB = tuple(x/255 for x in colorRGB)
print(f'colorRGB: {colorRGB}')
colorHSV = rgb_to_hsv(*colorRGB)
colorRGB = hsv_to_rgb(*colorHSV)
print(f'colorRGB: {colorRGB}')
Output:
colorRGB: (1.0, 0.0, 1.0)
colorRGB: (1.0, 0.0, 1.0)
If You explore colorsys
library code, You will observe function rgv_to_hsv
and hsv_to_rgv
code. You will observe there are multiple divisions and float multiplication happening. This is the reason it is library is returning float value.
You can convert float to int as:
colorRGB = list(map(int, hsv_to_rgb(colorHSV[0],colorHSV[1],colorHSV[2])))
Why is hsv_to_rgb
returning a float value for this? and only for g and b?
import colorsys
from colorsys import *
colorRGB = (255,0,255)
print(colorRGB)
colorHSV = rgb_to_hsv(colorRGB[0],colorRGB[1],colorRGB[2])
colorRGB = hsv_to_rgb(colorHSV[0],colorHSV[1],colorHSV[2])
print(colorRGB)
(255, 0, 255)
(255, 0.0, 255.0)
[Finished in 0.0s]
Solution
You need to rescale RGB values 0 to 255 between 0 to 1 first.
Section Code Modification below gives you a modified version of your code that will run bug-free.
If you try this, you would realize what is happening.
# we provide r, g, b values ranging between 0 and 1 for each.
colorsys.hsv_to_rgb(*colorsys.rgb_to_hsv(1,0,0))
Output:
(1, 0.0, 0.0)
Code Modification
I would change your code as follows (rescale 0-255 between 0-1):
from colorsys import hsv_to_rgb, rgb_to_hsv
colorRGB = (255,0,255)
colorRGB = tuple(x/255 for x in colorRGB)
print(f'colorRGB: {colorRGB}')
colorHSV = rgb_to_hsv(*colorRGB)
colorRGB = hsv_to_rgb(*colorHSV)
print(f'colorRGB: {colorRGB}')
Output:
colorRGB: (1.0, 0.0, 1.0)
colorRGB: (1.0, 0.0, 1.0)
If You explore colorsys
library code, You will observe function rgv_to_hsv
and hsv_to_rgv
code. You will observe there are multiple divisions and float multiplication happening. This is the reason it is library is returning float value.
You can convert float to int as:
colorRGB = list(map(int, hsv_to_rgb(colorHSV[0],colorHSV[1],colorHSV[2])))