2

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 ?

Simon Bergot
  • 10,378
  • 7
  • 39
  • 55
psychoslave
  • 2,783
  • 3
  • 27
  • 44

1 Answers1

16

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    What 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? – Gunjan naik Nov 20 '17 at 08:47
  • @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. – paxdiablo Aug 24 '18 at 00:25