Search code examples
pythongoogle-colaboratory

Show processed images in Google Colab


I want to display an image matrix variable on Google Colab, I have a function to change the BGR image to Grayscale, but if I display it using the function plt.imgshow() from matplotlib the image that comes out is not grayscale. I try to use the "image" function Image in IPython.display but the results don't come out, below is the script that I made

!wget "https://www.duckietown.org/wp-content/uploads/2018/05/duckietown_nice-1024x683.jpg" -O dt.jpg

import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
from IPython.display import Image

image = cv2.imread('./dt.jpg')

H, W = image.shape[:2]
gray = np.zeros((H, W), np.uint8)
for i in range(H):
  for j in range(W):
    gray[i, j] = np.clip(0.299 * image[i, j, 0] + 0.587 * image[i, j, 1] + 0.114 * image[i, j, 2], 0, 255)
imgGray = gray
Image(imgGray)

How do I fix this? is there a function that can display images on Google Colab besides the two functions above?


Solution

  • Do this. It'll show image in grayscale.

    import sys
    import numpy as np
    from matplotlib import pyplot as plt
    from IPython.display import Image
    
    image = cv2.imread('./dt.jpg')
    val = np.subtract(image,128)
    plt.imshow(np.abs(val), cmap=plt.get_cmap('gray'),vmin=0,vmax=255)
    plt.title('Image'), plt.xticks([]), plt.yticks([])
    plt.show()