Search code examples
imagetensorflowmatplotlibtensorflow2.0color-space

How to Plot YCBCR color space image with matplotlib?


This is my code it shows all color spaces except YCBCR ,,

Notation:ConvertLayer converts color space of image

fig=plt.figure(figsize=(9, 9))
for images, labels in train_ds.take(1):
    for i in range(16):
      plt.subplot(5, 5, i + 1)
      color_space = COLOR_SPACES[i%5]
      image = tf.expand_dims(images[i//5] ,axis=0)
      image = augmentation(NormalLayer(color_space)(tf.cast(image,tf.float32)))
      if color_space=="YCBCR":
        image = tf.cast(image, tf.uint8)
      image = ConvertLayer(color_space)(image)
      #image = tf.cast(image * 255.0, tf.uint8)
      lbl = "{}({})".format(class_names[labels[i//4].numpy().argmax()] , color_space )
      plt.imshow(tf.squeeze(image))
      plt.title(lbl)
      plt.axis("off")
    break

enter image description here

I need to visualize it just in matplotlib.


Solution

  • With the following code I was able to visualize the image in matplotlib.

    import matplotlib.pyplot as plt
    import numpy as np
    
    x=plt.imread("/content/car.jpeg")
    y=rgb2ycbcr(x)
    
    fig = plt.figure(figsize=(10, 7))
    rows = 1
    columns = 2
    
    fig.add_subplot(rows, columns, 1)
    plt.imshow(x)
    plt.axis('off')
    plt.title("RGB")
    
    fig.add_subplot(rows, columns, 2)
    plt.imshow(y)
    plt.axis('off')
    plt.title("YCBCR")
    
    def rgb2ycbcr(im):
        xform = np.array([[.299, .587, .114], [-.1687, -.3313, .5], [.5, -.4187, -.0813]])
        ycbcr = im.dot(xform.T)
        ycbcr[:,:,[1,2]] += 128
        return np.uint8(ycbcr)
    

    Output:

    enter image description here