How to split an image into different color channels in OpenCV Python?


A color image consists of three color channels- Red, Green and Blue. These color channels can be split using cv2.split() function. Let's look at the steps to split an image into different color channels-

  • Import the required library. In all the following examples, the required Python library is OpenCV. Make sure you have already installed it.

  • Read the input image using cv2.imread() method. Specify full path of image with the image type (i.e. png or jpg)

  • Apply cv2.split() function on the input image img. It returns blue, green and red channel pixel values as numpy arrays. Assign these values to variables blue, green and red.

blue,green,red = cv2.split(img)
  • Display three channels as gray images.

Let's have a look at some examples for clear understanding.

We will use this image as the Input File in the following examples −


Example

In this example, we split an input image into its constituent color channels: Blue, Green and Red. We also display these color channels grayscale images.

# import required libraries import cv2 # read the input color image img = cv2.imread('bgr.png') # split the Blue, Green and Red color channels blue,green,red = cv2.split(img) # display three channels cv2.imshow('Blue Channel', blue) cv2.waitKey(0) cv2.imshow('Green Channel', green) cv2.waitKey(0) cv2.imshow('Red Channel', red) cv2.waitKey(0) cv2.destroyAllWindows()

Output

When you run the above Python program, it will produce the following three output windows, each showing a color channel (blue, green and red) as a grayscale image.




Example

In this example, we split an input image into its constituent color channels: Blue, Green and Red. We also display these color channels color images (BGR).

# import required libraries import cv2 import numpy as np # read the input color image img = cv2.imread('bgr.png') # split the Blue, Green and Red color channels blue,green,red = cv2.split(img) # define channel having all zeros zeros = np.zeros(blue.shape, np.uint8) # merge zeros to make BGR image blueBGR = cv2.merge([blue,zeros,zeros]) greenBGR = cv2.merge([zeros,green,zeros]) redBGR = cv2.merge([zeros,zeros,red]) # display the three Blue, Green, and Red channels as BGR image cv2.imshow('Blue Channel', blueBGR) cv2.waitKey(0) cv2.imshow('Green Channel', greenBGR) cv2.waitKey(0) cv2.imshow('Red Channel', redBGR) cv2.waitKey(0) cv2.destroyAllWindows()

Output

When you run the above python program, it will produce the following three output windows each showing a color channel (blue, green and red) as a color image.




Updated on: 02-Dec-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements