index matrix

Hi,

In my code I need to create a matrix filled with all the possible pixel coordinates of an image ( Mat ).

ex.for a 1024x768 image: [ 0, 0] [ 0, 1] [ 0, 2] . . . [1024, 768]

Is there a more efficient way of doing this than:

void indexMatrix(Mat &matrix, int height, int width){

int cols = height*width;
int index = 0;

matrix = Mat::ones(cols, 2, CV_8UC1);

for( int col = 0; col < width; ++col ) {
for (int row = 0; row < height; ++row) {
matrix.at<uchar>(index,0) = col;
matrix.at<uchar>(index,1) = row;

index++;
}
}

edit retag close merge delete

what is your purpose of creating such a matrix?

( 2016-03-24 09:19:03 -0500 )edit

I need to use a warping algorithm. Given an image (the Mat mentioned above), each pixel has a depth value ( stored in another Mat). The algorithm takes a set of coordinates and warps them to new coordinates.

So for each row of this matrix, I shall calculate a new set of values.

I wish to parallelise this process. Hence why i have isolated it into a separate process.

( 2016-03-24 09:31:17 -0500 )edit

Sort by ยป oldest newest most voted

still i can't imagine how to use such a matrix but you can create it with findNonZero()

take a look at the code below

#include <opencv2/opencv.hpp>
using namespace cv;

int main( int argc, const char** argv )
{
Mat src= Mat::ones(5,5,CV_8UC1);
//std::vector<Point> locations;   // you can use vector or Mat to get same result
Mat locations;  // output, locations of non-zero pixels
findNonZero(src, locations);
std::cout << locations;
return 0;
}


output locations vector is like below you can reshape it if you want

[0, 0;
1, 0;
2, 0;
3, 0;
4, 0;
0, 1;
1, 1;
2, 1;
3, 1;
4, 1;
0, 2;
1, 2;
2, 2;
3, 2;
4, 2;
0, 3;
1, 3;
2, 3;
3, 3;
4, 3;
0, 4;
1, 4;
2, 4;
3, 4;
4, 4]

more

findNonZero is good solution if your first concern is a concise code. Otherwise, if you need performance, I would stick to your original approach and change

matrix.at<uchar>(index,0) = col;

matrix.at<uchar>(index,1) = row;

into

matrix.ptr<uchar>(index)[0] = col

matrix.ptr<uchar>(index)[1] = row

more

i agree that this approach might be faster. but matrix type should be CV_16U or CV_16S

( 2016-03-24 10:33:51 -0500 )edit

Indeed it was quicker, thank you both for your help.

( 2016-03-24 14:46:11 -0500 )edit