Search code examples
pythonopencvcolorscielab

Converting single value colors to LAB using python OpenCV


I have an numpy array containing a single pixel/color in floating point RGB. I need to convert this value to LAB, for which I am trying the following:

color = cv2.cvtColor(color.reshape((1,1,3)), cv2.COLOR_RGB2LAB).reshape((3))

Where color is: array([137.38841, 161.38841, 65.38841], dtype=float32)

The resulting LAB is: [100. 0. 0.]

Which clearly isn;t correct as it should be close to: [62.667494977600484, 22.98637993404601, 46.1397720707445]

How do I convert the value to LAB?


Solution

  • You were not reshaping it properly. Use the below code to do that.

    import cv2
    import numpy as np
    bgr = [40, 158, 16]
    lab = cv2.cvtColor( np.uint8([[bgr]] ), cv2.COLOR_BGR2LAB)[0][0]
    print(lab)  #[145  71 177]
    

    Above code will help of rgb/bgr value is in integer. Since your values are in floating-point, I suggest you go with rgbtolab function found on this link. https://stackoverflow.com/a/16020102/9320324