OpenCV: Matrix Iteration

2019-01-23 18:38发布

问题:

I am new to OpenCV. I am trying to use iterator instead of "for" loop, which is too slow for my case. I tried some codes like this:

MatIterator_<uchar> it, end;
for( it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it)
{
    //some codes here
}

My question here is: how can I convert a for loop like:

for ( int i = 0; i < 500; i ++ )
{
    exampleMat.at<int>(i) = srcMat>.at<int>( i +2, i + 3 )
}

into iterator mode? That is, how can I do the "i +2, i + 3" in iterator form? I only can get the corresponding value by " *it " I think, but I couldn't get its counting number. Many thanks in advance.

回答1:

It's not the for loop which is slow it is the exampleMat.at<int>(i) which is doing range checking.

To efficently loop over all the pixels you can get a pointer to the data at the start of each row with .ptr()

for(int row = 0; row < img.rows; ++row) {
    uchar* p = img.ptr(row);
    for(int col = 0; col < img.cols; ++col) {
         *p++  //points to each pixel value in turn assuming a CV_8UC1 greyscale image 
    }

    or 
    for(int col = 0; col < img.cols*3; ++col) {
         *p++  //points to each pixel B,G,R value in turn assuming a CV_8UC3 color image 
    }

}   


回答2:

You need some kind of counting variable and you will have to declare and update it yourself. A compact way of doing this would be

int i = 0;
for( it = I.begin<uchar>(), end = I.end<uchar>(); it != end; ++it,i++)
{
//some codes here involving i+2 and i+3
}

if you are looking for super fast access however I would recommend manipulating the data pointer yourself. For a great explanation of iterating speed look at OpenCV 2 Computer Vision Application Programming Cookbook on page 51 (65 in pdf). Your code might then look something lik

cv::Mat your_matrix;
//assuming you are using uchar
uchar* data = your_matrix.data();

for(int i = 0; i < some_number; i++)
{
  //operations using *data
  data++;
}