Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values of a Matrix which are non zero

Tags:

c++

opencv

I am translating some matlab code to c++ using opencv. I want to get the values of a Matrix which satisfies a condition. I created a mask for this and when I apply it to the original Matrix I get the same size of the original matrix but with 0 values which are not there in the mask. But my question is how can I get only the values that are non-zero in the matrix and assign it to a different matrix.

My matlab code is:

 for i= 1:size(no,1)
        mask= labels==i;
        op = orig(mask, :); //op only contains the values from the orig matrix which are in the mask. So orig size and op size is not the same
.....
end

The c++ translation that I have now is:

for (int i=0; i<n.rows; i++)
{
    Mat mask;
    compare(labels,i,mask,CMP_EQ);
    Mat op;
    orig.copyTo(op,mask); //Here the orig size and the op size is always same but values which are not in the mask are 0
}

So, how can I create a matrix which only has the values that the mask satisfies???

like image 321
user1583647 Avatar asked Nov 18 '13 11:11

user1583647


1 Answers

You might try to make use of cv::SparseMat (http://docs.opencv.org/modules/core/doc/basic_structures.html#sparsemat), which only keeps non-zero values in a hash.

When you assign a regular cv::Mat to a cv::SparseMat, it automatically captures the non-zero values. From that point, you can iterate through the non-zero values and manipulate them as you'd like.

Hope I got question correctly and it helps!

like image 193
emredog Avatar answered Oct 31 '22 12:10

emredog