Python Extracting Green Channels from Color Image

Python

OpenCV – Get blue channel from image

To extract the blue channel of the image, first read the color image using the Python OpenCV library and then extract the blue channel 2D array from the image array using the image clipping method.

 

Step by step procedure to extract Blue Channel of color image

Following is the sequence of steps to obtain the blue channel of a color image.

  1. Read the image using cv2.imread().
  2. imread() returns a BGR (Blue-Green-Red) array. It is a three-dimensional array i.e. 2D pixel array for three color channels.
  3. Extract the blue channel alone by accessing the array.

 

Example 1: Get the blue channel from the color image.

In the following example, we will do the above mentioned sequence of steps, to extract the Green Channel from the following image.

Image source or Input image

Python Program

import cv2
 
#read image
src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)
print(src.shape)

#extract blue channel
blue_channel = src[:,:,0]

#write blue channel to greyscale image
cv2.imwrite('D:/cv2-blue-channel.png',blue_channel) 

We have recorded the blue channel to an image. Since this is just a 2D array with values ​​from 0 to 255, the output looks like a grayscale image, but these are the blue channel values.

Output image (Blue channel)

Python OpenCV - Extracting Green Channels from Images

If you look at the triangles, one of the red and the green ones is darker than the other.

To display the image in blue, let’s make the red and green components zero.

Python Program

import cv2
import numpy as np

#read image
src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)
print(src.shape)

# extract blue channel
blue_channel = src[:,:,0]

# create empty image with same shape as that of src image
blue_img = np.zeros(src.shape)

#assign the red channel of src to empty image
blue_img[:,:,0] = blue_channel

#save image
cv2.imwrite('D:/cv2-blue-channel.png',blue_img) 

Output image

Python OpenCV - Extracting Green Channels from Images

 

Summary

In this guide of Python example we learned how to extract the blue channel from an image.

Hope this helps!

Source link

Share: