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.
In OpenCV the main matrix class is called Mat and is contained in the OpenCV-namespace cv. This matrix is not templated but nevertheless can contain different data types. These are indicated by a certain type-number. Additionally, OpenCV provides a templated class called Mat_, which is derived from Mat.
That is, image of type CV_64FC1 is simple grayscale image and has only 1 channel: image[i, j] = 0.5. while image of type CV_64FC3 is colored image with 3 channels: image[i, j] = (0.5, 0.3, 0.7) (in C++ you can check individual pixels as image.at<double>(i, j) ) CV_64F is the same as CV_64FC1 .
CV_8UC3 - 3 channel array with 8 bit unsigned integers. CV_8UC4 - 4 channel array with 8 bit unsigned integers. CV_8UC(n) - n channel array with 8 bit unsigned integers (n can be from 1 to 512) )
The Mat class of OpenCV library is used to store the values of an image. It represents an n-dimensional array and is used to store image data of grayscale or color images, voxel volumes, vector fields, point clouds, tensors, histograms, etc.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With