4daJKong
4daJKong

Reputation: 2067

how to change XYZ color space to RGB 0-255

I have XYZ dataset like that:

[[  15.4999257    20.91432805    8.15938343]
 [  38.47211872   41.38471882    4.41641215]
 [   8.42304194   10.26972173    4.58244444]
 [  59.15345728   65.6834669    42.20671404]
 [  48.21549352   50.67621445    7.84460441]
 [  28.5987903    29.48986333   25.78866701]
 [  16.37042029   11.17896503   20.92325834]...]

I want to change it to RGB 0-255:

import numpy as np

XYZ_to_RGB_matrix = [
    [3.24062548, -1.53720797, -0.49862860],
    [-0.96893071, 1.87575606, 0.04151752],
    [0.05571012, -0.20402105, 1.05699594]]

my_rgb = (np.dot(XYZ_to_RGB_matrix, xyz_test) * 255).astype('uint8')

xyz_test is only one row array from XYZ dataset,

However, I found the result didn't correspond the right label,

for example, XYZ:[ 15.4999257 20.91432805 8.15938343] its label is green leaf but my rgb result is [244 116 51] it is not green, so is there some mistakes in my code?

Upvotes: 2

Views: 4677

Answers (1)

Zephyr
Zephyr

Reputation: 12514

Try this code:

from colormath.color_objects import sRGBColor, XYZColor
from colormath.color_conversions import convert_color

XYZ = [[15.4999257, 20.91432805, 8.15938343],
       [38.47211872, 41.38471882, 4.41641215],
       [8.42304194, 10.26972173, 4.58244444],
       [59.15345728, 65.6834669, 42.20671404],
       [48.21549352, 50.67621445, 7.84460441],
       [28.5987903, 29.48986333, 25.78866701],
       [16.37042029, 11.17896503, 20.92325834]]

RGB = []

for xyz_list in XYZ:
       xyz = XYZColor(*[component/100 for component in xyz_list])
       rgb = convert_color(xyz, sRGBColor)
       rgb_list = [255*color for color in rgb.get_value_tuple()]
       RGB.append(rgb_list)

print(RGB)

With this code I get this output as RGB matrix:

[92.22372010136964, 137.4037125386466, 78.86090637192737]
[189.9967785535171, 173.00440159210268, 0.0]
[77.62483771390573, 95.56815462725146, 61.177682509553435]
[201.10203247049455, 216.97942244866422, 185.00583953450555]
[211.2583657458791, 187.8058726835025, 47.400682365292234]
[147.26702521874506, 147.4599728158739, 152.30904210885427]
[131.7100385873106, 69.84477339437986, 144.29850008120889]

Note that you have to install the required package:

pip install colormath

Upvotes: 1

Related Questions