Grayscale images have only one channel. Therefore, some differences are introduced when working with these images. We are going to highlight these differences here.
Again, we will use the cv2.imread() function to read an image. In this case, the second argument is needed because we want to load the image in grayscale. The second argument is a flag specifying the way the image should be read. The value that's needed for loading an image in grayscale is cv2.IMREAD_GRAYSCALE:
# The function cv2.imshow() is used to display an image in a window
# The first argument of this function is the window name
# The second argument of this function is the image to be shown.
# In this case, the second argument is needed because we want to load the image in grayscale.
# Second argument is a flag specifying the way the image should be read.
# Value needed for loading an image in grayscale: 'cv2.IMREAD_GRAYSCALE'.
# load OpenCV logo image:
gray_img = cv2.imread('logo.png', cv2.IMREAD_GRAYSCALE)
In this case, we store the image in the gray_img variable. If we get the dimensions of the image (using gray_img.shape), we will get only two values that is, rows and columns. In grayscale images, the channel information is not provided:
# To get the dimensions of the image use img.shape
# If color image, img.shape returns returns a tuple of number of rows, columns and channels
# If grayscale, returns a tuple of number of rows and columns.
# So, it can be used to check if the loaded image is grayscale or color image.
# Get the shape of the image (in this case only two components!):
dimensions = gray_img.shape
img.shape will return the dimensions of the image in a tuple, like this—(99, 82).
A pixel value can be accessed by row and column coordinates. In grayscale images, only one value is obtained (usually called the intensity of the pixel). For example, if we want to get the intensity of the pixel (x=40, y=6), we would use the following code:
# You can access a pixel value by row and column coordinates.
# For BGR image, it returns an array of (Blue, Green, Red) values.
# Get the value of the pixel (x=40, y=6):
i = gray_img[6, 40]
The pixel values of the image can be also modified in the same way. For example, if we want to change the value of the pixel (x=40, y=6) to black (intensity equals to 0), we would use the following code:
# You can modify the pixel values of the image in the same way.
# Set the pixel to black:
gray_img[6, 40] = 0