Ask Your Question
1

index matrix

asked 2016-03-24 07:13:18 -0600

mark92m gravatar image

updated 2016-03-24 07:14:45 -0600

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 flag offensive close merge delete

Comments

what is your purpose of creating such a matrix?

sturkmen gravatar imagesturkmen ( 2016-03-24 09:19:03 -0600 )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.

mark92m gravatar imagemark92m ( 2016-03-24 09:31:17 -0600 )edit

2 answers

Sort by ยป oldest newest most voted
4

answered 2016-03-24 09:48:03 -0600

updated 2016-03-24 09:55:30 -0600

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]
edit flag offensive delete link more
1

answered 2016-03-24 10:09:31 -0600

acajic gravatar image

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

edit flag offensive delete link more

Comments

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

sturkmen gravatar imagesturkmen ( 2016-03-24 10:33:51 -0600 )edit

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

mark92m gravatar imagemark92m ( 2016-03-24 14:46:11 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2016-03-24 07:13:18 -0600

Seen: 4,342 times

Last updated: Mar 24 '16