accessing pixels in an image
There are three possible ways to access image pixels
Method One: pointer access
The pointer accesses the fastest, and the mat class can get the first address of any line of the image through the PTR function.
Also, some properties of the mat class can be used with public properties rows and cols to represent rows and columns
The number of channels can be obtained by channels () function;
void VisitPix1 ()
{
Mat srcimg = Imread ("Jpg/1.jpeg");
Mat dstimg;
Srcimg.copyto (DSTIMG);
int rowNum = dstimg.rows;
int colnum = Dstimg.cols*dstimg.channels ();
for (int row = 0;row<rownum;row++)
{
uchar* data = srcimg.ptr<uchar> (row);
for (int col = 0;col<colnum;col++)
{
data[col]+=23;
}
}
Imshow ("src", srcimg);
Imshow ("DST", dstimg);
Waitkey ();
}
Method Two: Iterator access
The pixel is accessed through an iterator. You can get begin and end, and you can get the address content with the X operator only from the begin iteration to the end
void visitPix1 ()
{
Mat srcimg = Imread ("Jpg/1.jpeg");
Mat dstimg;
Srcimg.copyto (DSTIMG);
Mat_<vec3b>::iterator begin = Dstimg.begin<vec3b> ();
Mat_<vec3b>::iterator end = Dstimg.end<vec3b> ();
for (Mat_<vec3b>::iterator it = begin;it!=end;it++)
{
(*it) [0] + +;
(*it) [1] +=13;
(*it) [2] +=14;
}
Imshow ("src", srcimg);
Imshow ("DST", dstimg);
Waitkey ();
}
Method Three: Dynamic address calculation
An at method can be introduced here, at (int y,int x) can be used to access the image, but requires the conversion of the data type
img.at<vec3b> (j,i) [Channel] = Value
void VisitPix3 ()
{Mat srcimg = Imread ("Jpg/1.jpeg");
Mat dstimg;
Srcimg.copyto (DSTIMG);
int rowNum = dstimg.rows;
int colnum = Dstimg.cols*dstimg.channels ();
for (int row = 0;row<rownum;row++)
{
for (int col = 0;col<colnum;col++)
{
Dstimg.at<vec3b> (Row,col) [0] +=23;
Dstimg.at<vec3b> (Row,col) [1] +=23;
Dstimg.at<vec3b> (Row,col) [2] +=23;
}
}
Imshow ("src", srcimg);
Imshow ("DST", dstimg);
Waitkey ();
}
Also add a function
Timing functions
There are two functions GetTickCount and gettickfrequency that can be timed in OPENCV
The GetTickCount function returns the number of clock cycles that the CPU has traversed since an event
The Gettickfrequency function returns the number of clock cycles that the CPU has walked in a second,
Example
void Timetest ()
{
Double TIME0 = static_cast<double> (GetTickCount ());
for (int i =0;i<100000;i++) {}
TIME0 = (double) (GetTickCount ()-TIME0)/gettickfrequency ();
cout<< "Run Time" <<time0<< "SEC" <<endl;
}
OpenCV three ways to access image pixels