How to split images into different channels in OpenCV using C++?

OpenCVC++Server Side ProgrammingProgramming

There are three channels in an RGB image- red, green and blue. The color space where red, green and blue channels represent images is called RGB color space. In OpenCV, BGR sequence is used instead of RGB. This means the first channel is blue, the second channel is green, and the third channel is red. To split an RGB image into different channels, we need to define a matrix of 3 channels. We use 'Mat different_Channels[3]' to define a three-channel matrix.

Next, we split the loaded image using OpenCV 'split()' function. The format of this function is 'split(Source Matrix, Destination Matrix)'. This function split the images of the source matrix into the channels the image and save them in the destination matrix. This line is operating – 'split(myImage, different_Channels);'

The split function has already loaded the blue, green and red channel into the 'different_channels' matrix. Using the following lines, we loaded the images stored in different channels into new matrices.

Mat b = different_Channels[0];//loading blue channels//
Mat g = different_Channels[1];//loading green channels//
Mat r = different_Channels[2];//loading red channels//

And finally we showed each channel differently using the following lines −

imshow("Blue Channel",b);//showing Blue channel//
imshow("Green Channel",g);//showing Green channel//
imshow("Red Channel",r);//showing Red channel//

This is how we can split an images into its channels.

The following program splits an RGB image into blue, green, and red channel.

Example

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc,const char** argv) {
   Mat myImage;//declaring a matrix to load the image//
   Mat different_Channels[3];//declaring a matrix with three channels//  
   myImage= imread("RGB.png");//loading the image in myImage matrix//
   split(myImage, different_Channels);//splitting images into 3 different channels//  
   Mat b = different_Channels[0];//loading blue channels//
   Mat g = different_Channels[1];//loading green channels//
   Mat r = different_Channels[2];//loading red channels//  
   imshow("Blue Channel",b);//showing Blue channel//
   imshow("Green Channel",g);//showing Green channel//
   imshow("Red Channel",r);//showing Red channel//
   imshow("Actual_Image", myImage);//showing actual image//
   waitKey(0);//wait for key stroke
   destroyAllWindows();//closing all windows//
   return 0;
}

Output

raja
Published on 10-Mar-2021 12:19:22
Advertisements