Search code examples
python-3.xopencvcolor-space

While using opencv why one of my channel values became zero?


Where did I make a mistake during hsv conversion? why am I losing data in my array which is the correct way to convert to hsv image?

*Note: In my requirement, I need to feed PIL images to cvt.Color(), But I am losing the data during this process? is there any way I can still perform this action using PIL images in OpenCV?

image = PIL.Image.open("112.jpg")
data = np.asarray(image)                      #Feeding the same  RGB array
y1=cv2.cvtColor(np.float32(data),cv2.COLOR_RGB2HSV)
y1 = y1.astype(np.uint8)

>>  y1
>>> array([[[ 52,   0, 252],
    [ 52,   0, 252],
    [ 52,   0, 252],
    ...,
    [ 59,   0, 186],
    [ 59,   0, 186],
    [ 59,   0, 186]],

   [[ 52,   0, 252],
    [ 52,   0, 252],
    [ 52,   0, 252],
    ...,
    [ 59,   0, 186],
    [ 59,   0, 186],
    [ 59,   0, 186]],

   [[ 52,   0, 252],
    [ 52,   0, 252],
    [ 52,   0, 252],
    ...,
    [ 59,   0, 187],
    [ 59,   0, 187],
    [ 59,   0, 187]],

   ...,

Similarly,

image = PIL.Image.open("112.jpg")
data = np.asarray(image)                      #Feeding the same  RGB array
y1=cv2.cvtColor(data,cv2.COLOR_RGB2HSV)
y1 = y1.astype(np.uint8)

>>> array([[[ 26,  54, 252],
    [ 26,  54, 252],
    [ 26,  54, 252],
    ...,
    [ 30, 151, 186],
    [ 30, 151, 186],
    [ 30, 151, 186]],

   [[ 26,  54, 252],
    [ 26,  54, 252],
    [ 26,  54, 252],
    ...,
  1. why is float32 making on one of my channel zero. Which one is the correct method of conversion?

Test Image: enter image description here


Solution

  • For float32 formats there are other ranges of values.

    For RGB image it is range [0.0,1.0].

    For HSV:

    uint8 - H[0,180], S[0,255], V[0,255]

    float32 - H[0.0,360.0], S[0.0,1.0], V[0.0,1.0]

    This is the right way to convert HSV float32 to uint8:

    img1=cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
    print(img1[0,0])
    
    img = img.astype(np.float32)/255
    img2=cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
    print((img2[0,0]*np.array([0.5,255,255],np.float32)).astype(np.uint8))