pythonscikit-image

Get Hex value from LAB color space


How to get Hex from LAB color space?

There is an online converter https://www.nixsensor.com/free-color-converter/, but I need an automatic call.

I tried to use https://scikit-image.org/docs/stable/api/skimage.color.html#skimage.color.lab2rgb function to get RBG color space and then convert to Hex, using colormap.rgb2hex for instance.

How do I call the lab2rgb function? It receives an image as an array.

Example:

LAB values: [94.4, -1.22, -0.13] Return Hex value: #ECF0EF

from skimage import color

lab_color = [[[94.4, -1.22, -0.13]]]
rgb_color = color.lab2rgb(lab_color, illuminant='D65', observer='2')
print(rgb_color)

Solution

  • You were nearly there, you just omitted scaling up to the range 0..255

    #!/usr/bin/env python3
    
    from skimage import color
    
    # Define a Lab colour
    lab_color = [[[94.4, -1.22, -0.13]]]
    
    # Convert to RGB and extract R,G and B components, then scale to 0..255
    rgb_color = color.lab2rgb(lab_color, illuminant='D65', observer='2')
    r = round(rgb_color[0,0,0] * 255)
    g = round(rgb_color[0,0,1] * 255)
    b = round(rgb_color[0,0,2] * 255)
    
    # Format up as hex string, i.e. #ECF0EF
    res = f'#{r:02X}{g:02X}{b:02X}'