Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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]

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]

6]