pythonrgbcolormath

Conversion RGB to xyY with colormath


With colormath I make a conversion from RGB to xyY value. It works fine for 1 RGB value, but I can't find the right code to do the conversion for multiple RGB values imported from an Excel. I use to following code:

from colormath.color_objects import sRGBColor, xyYColor
from colormath.color_conversions import convert_color
import pandas as pd

data = pd.read_excel(r'C:/Users/User/Desktop/Color/Fontane/RGB/FontaneHuco.xlsx')
df = pd.DataFrame(data, columns=['R', 'G', 'B'])
#print(df)


rgb = sRGBColor(df['R'],df['G'],df['B'], is_upscaled=True)
xyz = convert_color(rgb, xyYColor)

print(xyz)

But when i run this code i receive to following error:

Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\pythonProject4\Overige\Chroma.py", line 9, in <module>
    lab = sRGBColor(df['R'], df['G'], df['B'])
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\colormath\color_objects.py", line 524, in __init__
    self.rgb_r = float(rgb_r)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\series.py", line 141, in wrapper
    raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'float'>

Does anyone has an idea how to fix this problem?

Excel dataframe


Solution

  • convert_color is expecting floats and you're giving it dataframe columns instead. You need to apply the conversion one row at at time, which can be done as follows:

    xyz = df.apply(
        lambda row: convert_color(
            sRGBColor(row.R, row.G, row.B, is_upscaled=True), xyYColor
        ),
        axis=1,
    )