OpenCV with Python for Beginners : Day 6

How to split an image into color channels

Splitting an image into its color channels (like in RGB: Red, Green, Blue) allows us analyse and manipulate each color component. This method is used in various applications, from enhancing specific colors in images to isolating objects based on color. 

Each channel of image represents the intensity of a specific color. By splitting the image, we can examine each color component separately, it let us to understand how much of each color is present in different parts of the image

In computer vision and image processing, by splitting channels we can isolate objects of interest based on their color. For example, we could isolate green objects by analyzing the green channel.

 In this post, we will learn how visualize the color channels of an RGB image using OpenCV with Python.

Step 1: For this exercise download the image

Load the image as code below:

Step 2: The function cv2.split() split a multi-channel/colored array into separate single-channel arrays. It will return an array with the three channels, each of which corresponds to blue, green, and red channels represented as an array with two dimensions.

Step 3: Show the images on separate windows as de code below:

Save and run the script, the result should be like this:

Step 4: The next step is to merge the images by the method cv2.merge() it takes single channel images and combines them to make a multi-channel image. Add the code as below:

Save and run the script.

Step 5: Finally save the channels images separated

The result should be like this:

Please take a look the final code


#Import the library cv2
import cv2

#Create the path variable
img_path = 'img/rgb.png'

#variable to read the image
img_ = cv2.imread(img_path)

#splitting image in channels b,g,r
b,g,r = cv2.split(img_)

#Show channels on windows
cv2.imshow('Blue channel',b)
cv2.imshow('Green channel',g)
cv2.imshow('Red channel',r)

#Merge channels into a BGR image
original_img = cv2.merge((b,g,r))
cv2.imshow('Merged',original_img)

#Create image files from channels
cv2.imwrite('img/blue_channel.jpg',b)
cv2.imwrite('img/green_channel.jpg',g)
cv2.imwrite('img/red_channel.jpg',r)

cv2.waitKey(0)

cv2.destroyAllWindows()

On this tutorial we learned how to separate an image per channel for further analysis.

Comments are closed