Ask Your Question
0

get values of nonZero elements of a 2-dim cv::Mat

asked 2017-06-22 03:55:53 -0500

pouya.1991 gravatar image

I want to get values of nonZero elements of a 2-dim cv::Mat and put the result on a cv::Mat. How I can do this ? I used following code to get the index of nonZero elements :

cv::vector<cv::vec2i> nonzero ;

cv::findNonZero(mask,nonzero);

edit retag flag offensive close merge delete

Comments

and the problem is ?

berak gravatar imageberak ( 2017-06-22 03:59:07 -0500 )edit

findNonZero function get index of nonZero elements, but I want value of them. I can get value of the first nonZero element by using nonzero.at(1), but How I can put all values in a cv::Mat ?

pouya.1991 gravatar imagepouya.1991 ( 2017-06-22 04:18:42 -0500 )edit

you can make a new Mat with the nonzero elements (say, all on a single row), but a 2d Mat ? what about the "holes" ?

what do you need it for ?

berak gravatar imageberak ( 2017-06-22 04:22:08 -0500 )edit

who I can make a new with with the nonzero elements ? I have a probability matrix (mask) and want probability of the nonzero elements for a classification task.

pouya.1991 gravatar imagepouya.1991 ( 2017-06-22 04:28:27 -0500 )edit

still unclear. which shape is required for the classification task ? any ?

berak gravatar imageberak ( 2017-06-22 04:42:01 -0500 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2017-06-22 04:49:51 -0500

berak gravatar image

updated 2017-06-22 04:59:21 -0500

if the shape of the resulting Mat does not matter, you could simply line up your nonzero values like pearls on a string (bummer is: you'll lose the index information, this way):

Mat_<uchar> A(3,3); // demo data
A << 1,0,0,1,2,3,4,0,6;
cerr << A << endl;

vector<Point> nz; // rather use Point, than Vec2i, see below
findNonZero(A,nz);
cerr << Mat(nz);

Mat nonzeros;
for (Point p : nz) {
    nonzeros.push_back(A.at<uchar>(p)); // collect values
}
cerr << nonzeros << endl;

[  1,   0,   0;
   1,   2,   3;
   4,   0,   6]
[0, 0;
 0, 1;
 1, 1;
 2, 1;
 0, 2;
 2, 2]
[  1;
   1;
   2;
   3;
   4;
   6]
edit flag offensive delete link more

Comments

1

thanks, this code solves my problem, there is no way do to this job without for loop ?

pouya.1991 gravatar imagepouya.1991 ( 2017-06-22 05:03:15 -0500 )edit

hmm, i don't think so. (at least, i cannot think of any way)

berak gravatar imageberak ( 2017-06-22 05:19:27 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2017-06-22 03:55:53 -0500

Seen: 1,288 times

Last updated: Jun 22 '17