OpenCV Learning (5) image pixel access, color channel separation and fusion

Source: Internet
Author: User

The code is a primer on opencv3.0 programming from the Mao Nebula.

1. Chronograph function
GetTickCount () and gettickfrequency () functions;
The getTickCount () function returns the clock cycle that the CPU has traversed since an event;
The gettickfrequency () function returns the number of cycles that the CPU has walked in a second;

Case:

double time0=static_castdouble//记录起始时间// 事件的处理操作time0=((double)getTickCount()-time0)/getTickFrequency();cout<<"此方法的运行时间为:"<< time0<<"秒"<< endl;

2. Access three types of methods in image pixels:
1) "Method One" pointer access: c operator [];
2) "Method two" iterator iterator;
3) "Method three" dynamic address calculation;

Main program code:

#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>using namespace STD;using namespaceCvvoidColorreduce (mat& inputimage, mat& outputimage,intDIV);intMain () {//"1" creates the original diagram and displaysMat srcimage = Imread ("1.jpg"); Imshow ("Original image", srcimage);//"2" is created by the parameter specifications of the original diagramMat Dstimage; Dstimage.create (Srcimage.rows,srcimage.cols,srcimage.type ());//The same size and type as the original picture    //"3" Record start time    DoubleTIME0 =static_cast<Double> (GetTickCount ());//"4" Call color space reduction functionColorreduce (Srcimage,dstimage, +);//"5" calculates run time and outputsTIME0 = ((Double) GetTickCount ()-TIME0)/gettickfrequency ();cout<<"\ t This method runs at:"<<time0<<"Seconds"<<endl;//Output run time    //"6" DisplayImshow ("", dstimage); Waitkey (0); }

"Method One" pointer access: c operator [];
The fastest, but a bit abstract;

voidColorreduce (mat& inputimage, mat& outputimage,int Div)  {//Parameter PreparationOutputimage = Inputimage.clone ();//Copy argument to temp variable    intRowNumber = outputimage.rows;//number of rows    intColnumber = Outputimage.cols*outputimage.channels ();//Columns x number of channels = number of elements per row    //double loop, traverse all pixel values     for(inti =0; i < rownumber;i++)//Line loop{uchar* data = outputimage.ptr<uchar> (i);//Get the first address of line I         for(intj =0; J < colnumber;j++)//Column loops{//---------"Start processing each pixel"-------------DATA[J] = data[j]/Div*Div+Div/2;//----------"Processing End"---------------------}//Line processing end}  }

Mat class: Public member variables cols and rows give the image width and height, the member function channels () is used to return the image of the number of channels;
Number of pixels per line: ' int colnumber=outputimage.cols*outputimage.channels ();
The Mat class provides the PTR function to get the first address of any row in the image. PTR is a template function that returns the first address of line I;
unchar* Data =outputimage.ptr< uchar> (i);//Obtaining the first address of line I;

"Method two" iterator iterator;

void Colorreduce (mat& inputimage, mat& outputimage, intDiv)  {//Parameter PreparationOutputimage = Inputimage.clone ();//Copy argument to temp variable   //Get iteratorsMat_<vec3b>::iteratorit= Outputimage.begin<vec3b> ();//Initial position of the iteratorMat_<vec3b>::iterator itend = outputimage.End<Vec3b> ();//end-of-position iterator   //Access color image pixels     for(;it! = itend;++it)      {//------------------------"Start processing each pixel"--------------------(*it)[0] = (*it)[0]/Div*Div+Div/2; (*it)[1] = (*it)[1]/Div*Div+Div/2; (*it)[2] = (*it)[2]/Div*Div+Div/2;//------------------------"Processing End"----------------------------}  }

All we need in an iterator is to get the begin and end of the image matrix, and add the * operator to the iterator pointer to access the current point;

3) "Method three" dynamic address calculation;

void Colorreduce (mat& inputimage, mat& outputimage, intDiv)  {//Parameter PreparationOutputimage = Inputimage.clone ();//Copy argument to temp variableint rowNumber = outputimage.rows;//number of rowsint colnumber = Outputimage.cols;//Number of columns   //Access color image pixels     for(int i =0; i < rownumber;i++) { for(Int j =0; J < colnumber;j++) {//------------------------"Start processing each pixel"--------------------Outputimage. at<Vec3b> (I,J) [0] = Outputimage. at<Vec3b> (I,J) [0]/Div*Div+Div/2;//Blue channelOutputimage. at<Vec3b> (I,J) [1] = Outputimage. at<Vec3b> (I,J) [1]/Div*Div+Div/2;//Green channelOutputimage. at<Vec3b> (I,J) [2] = Outputimage. at<Vec3b> (I,J) [2]/Div*Div+Div/2;//Red is the channel           //-------------------------"Processing End"----------------------------}//Line processing end}  }

Dynamic address operation with the Colorreduce function of the At method;

3. Separation of color channels, multi-channel image blending
1) Channel separation: Split () function;
The C + + version of the split () function has two prototypes, respectively:
void Split (const mat& src,mat* mvbegin);
void Split (Inputarray m,outputarrayofarrays MV);
The first parameter, the Inputarray type of M or the const mat& type SRC, is a multi-channel array that needs to be detached;
The second parameter, the outputarrayofarrays type of MV, the output array of the Fill function, or the vector container of the output.
Let's look at an example together.

vector<Mat> channels;Mat imageBlueChannel;Mat imageGreenChannel;Mat imageRedChannel;srcImage4= imread("dota.jpg");// 把一个 3 通道图像转换成 3 个单通道图像split(srcImage4,channels);//分离色彩通道imageBlueChannel = channels.at(0);imageGreenChannel = channels.at(1);imageRedChannel = channels.at(2);

The above code first makes the relevant type declaration, then converts the loaded 3-channel image into 3 single-channel images, puts it into the vector-type channels, and then assigns the reference value.
According to OpenCV's BGR color space (blue, green, red, blue and green), where channels.at (0) represents the blue component of the reference extraction channels, channels.at (1) means that the reference is taken out channels The green color component in the channels.at (2) represents the red component of the reference taken out of the channels.
The split () function that separates a multi-channel array into several single-channel arrays is probably all of the above, so let's take a look at the merge () function, which is closely related to it.

2) Channel merging: merge () function;
Is still an example that combines the use of the split () function with the merge () function, first splitting the channel of the image, and then merging the channels. The specific code is shown below.

//define some Mat objects  Mat srcimage= Imread ( "1.jpg" ); Mat Imagebluechannel, Imagegreenchannel, imageredchannel,mergeimage; //defines the Mat vector container to hold the data after splitting  vector  <mat>  Channels;//Channel split  split (Srcimage,channels); //extract data for three-color channels  Imagebluechannel = channels.at (0 ) ; Imagegreenchannel = channels.at (1 ); imageredchannel = channels.at (2 ); //the split channel data merge  merge (Channels,mergeimage); //shows the final merge effect  imshow ( "Mergeimage" , mergeimage);  

These are the split () functions and the merge () functions and usages of the pair doing the opposite. Also, if we need to extract a specific single-channel array from a multi-channel array, or implement some complex channel combinations, you can use the Mixchannels () function.

Take one of the blue channels as an example:

#include <opencv2/core/core.hpp>#include <opencv2/highgui/highgui.hpp>#include <iostream>using namespaceCvusing namespace STD;intMain () {Mat srcimage; Mat Logoimage; vector<Mat>Channels    Mat Imagebluechannel;    Mat Imagegreenchannel; Mat Imageredchannel;//================= "Blue channel section" =================    //"1" read in pictureLogoimage = Imread ("Dota_logo.jpg",0); Srcimage = Imread ("Dota_jugg.jpg");if(!logoimage.data) {printf("Oh,no, read logoimage error!" \ n ");return false; }if(!srcimage.data) {printf("Oh,no, read srcimage error!" \ n ");return false; }//"2" converts a 3-channel image into 3 single-channel imagesSplit (srcimage, Channels);//Separate color channels    //"3" returns the blue channel reference of the original image to Imagebluechannel, note is a reference, equivalent to both, modify one of the other to changeImagebluechannel = channels.at (0);//"4" weighted the area at the bottom right of the blue Channel (500,250) of the original image and the logo map, and the resulting mixed results are stored in the Imagebluechannel. Simply speaking, the blue channel of the original is replaced with the logo to replace the blue channel. Addweighted (Imagebluechannel (Rect ( -, -, Logoimage.cols, logoimage.rows)),1.0, Logoimage,0.5,0, Imagebluechannel (Rect ( -, -, Logoimage.cols, logoimage.rows));//"5" to re-merge three single channels into a three-channelMerge (Channels,srcimage);//"6" DisplayNamedwindow ("<1> original painting +logo blue channel"); Imshow ("<1> original painting +logo blue channel", srcimage); Waitkey (0);return 0;}

OpenCV Learning (5) image pixel access, color channel separation and fusion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.