Converting a [0-255] integer range to a [0.0-1.0] float range
14,891
You can just divide each element by 255 (or 256 depending on whether you want the upper range to include or exclude 1):
pax> python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> rgbvar1 = [80,160,240] ; rgbvar1
[80, 160, 240]
>>> rgbvar2 = [x / 255.0 for x in rgbvar1] ; rgbvar2
[0.3137254901960784, 0.6274509803921569, 0.9411764705882353]
>>> rgbvar3 = [round(x * 255) for x in rgbvar2] ; rgbvar3
[80, 160, 240]
As you can see from rgbvar3
, you can use a similar method to convert them back.
To check that this works, the following may help:
>>> for i in range(256):
... j = i / 255.0
... k = round(j * 255)
... if i != k:
... print('Bad at %d'%(i))
...
>>>
The fact that it shows no errors for the expected possible input values (integers 0
through 255
) means that the reverse operation should work okay.
Comments
-
psychoslave almost 2 years
In WxWidget colors are represented by a RGB integer triplet. To interact with other libraries using a [0.0-1.0] float triplet representation, a conversion is needed.
Is there such a conversion function already existing in WxPython, Numpy or Python ?
-
Gunjan naik over 6 yearsWhat if we wanted to do the reverse operation? That is given rgbvar2 into [0,255] range. Does multiplying by 255 will solve the issue? Will it fail for very small decimal values?
-
paxdiablo over 5 years@user3515225, in the interests of responding quickly to questions posed about my answers, yes, it will work for the expected domain :-) See the update to the answer for more detail.