In image processing some tines we need to separate the channels of image. This is needful to achieve the required contrast of the image. Because some times if we remove the one or more channels from the image we can get better understanding of the image under consideration. In some cases we have to process only few channels of the image rather than the entire image. Open cv provides the functions to achieve the same. We can do the same thing with out using the functions of the open cv.
Fallowing code snippet is useful for splitting the image channels:
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <conio.h>
void main()
{
IplImage *Simg;
IplImage *Rimg;
IplImage *Gimg;
IplImage *Bimg;
int nrows,ncols;
Simg=cvLoadImage("E:/test.jpg");
Rimg=cvCreateImage(cvSize(Simg->width,Simg->height),Simg->depth,3);
Gimg=cvCreateImage(cvSize(Simg->width,Simg->height),Simg->depth,3);
Bimg=cvCreateImage(cvSize(Simg->width,Simg->height),Simg->depth,3);
cvNamedWindow("Red",0);
cvNamedWindow("Green",0);
cvNamedWindow("Blue",0);
cvResizeWindow("Red",320,320);
cvResizeWindow("Green",320,320);
cvResizeWindow("Blue",320,320);
nrows=Simg->height;
ncols=Simg->width;
for(int i=0;i<nrows*ncols*3;i++)
{
Rimg->imageData[i]=0;
Gimg->imageData[i]=0;
Bimg->imageData[i]=0;
}
for(int i=0;i<nrows*ncols*3;i+=3)
{
Rimg->imageData[i+2]=Simg->imageData[i+2];
Gimg->imageData[i+1]=Simg->imageData[i+1];
Bimg->imageData[i]=Simg->imageData[i];
}
cvShowImage("Red",Rimg);
cvShowImage("Green",Gimg);
cvShowImage("Blue",Bimg);
cvWaitKey(0);
_getch();
}
for example consider the image with three channels. Load that image into the memory with the help of Open CV. Next create the three images with the same size,depth and channels. Fill the entire image with the zeros means with black pixels. Now extract the individual channels from the original image and store them in the newly created images. Open cv changes the order of the pixels to BGR instead of RGB.
If we apply the ->height and ->width on the image in Open CV we will get the number of rows and columns. But actually if the image is color we have columns more than what we get. that is if we have width as 20 the actual columns on the disk is 60 because each channel will store in separate byte. In memory they will be stored in interleaved manner. So to get the red pixels we need to get the alternate pixels with the gap of two.
By running the above code on the below image:
we will get the fallowing images:
This comment has been removed by the author.
ReplyDeleteThe code mentioned here is useful for the images having three channels. This code is not tested on the images having four channels (Alpha and RGB)
ReplyDelete