Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a [0-255] integer range to a [0.0-1.0] float range

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 ?

like image 738
psychoslave Avatar asked May 17 '26 05:05

psychoslave


1 Answers

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.

like image 159
paxdiablo Avatar answered May 18 '26 19:05

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!