Ask Your Question

How to get values of a Matrix which are non zero

asked 2013-11-18 05:51:33 -0500

adt gravatar image

updated 2020-10-01 12:11:58 -0500

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

The c++ translation that I have now is:

for (int i=0; i<n.rows;i++)
            Mat mask;
               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???

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-11-18 10:53:16 -0500

updated 2013-11-18 10:55:30 -0500

The setTo function will do what you want.

Mat img;
img.setTo(255, mask);

all elements which are non-zero in mask will change to 255 in img.

edit flag offensive delete link more
Login/Signup to Answer

Question Tools


Asked: 2013-11-18 05:51:33 -0500

Seen: 2,114 times

Last updated: Nov 18 '13