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

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 ;

edit retag close merge delete

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 ?

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 ?

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.

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

Sort by » oldest newest most voted

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]

more

1

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

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

Official site

GitHub

Wiki

Documentation