How to get non-zero matrix values

I translated some matlab code in C ++ using opencv. I want to get the values ​​of a matrix that satisfies the 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 ​​that are not in the mask. But my question is how to get only values ​​other than zero in the matrix and assign them to another 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 

Now I have a C ++ translation:

 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 that has only values ​​that match the mask?

+7
c ++ opencv
source share
3 answers

You can try using cv :: SparseMat ( http://docs.opencv.org/modules/core/doc/basic_structures.html#sparsemat ), which only stores non-zero values ​​in the hash.

When you assign a regular cv :: Mat to cv :: SparseMat, it automatically captures non-zero values. From now on, you can iterate over nonzero values ​​and manipulate them as you would like.

Hope my question is right and it helps!

+4
source share

OpenCv supports Matrix Expresions, such as A > B or A <= B , etc.

This is stated in Documentation off cv :: Mat

0
source share

If you just want to store values, the Mat object is probably not the best way, since it was created for the purpose of storing images.

In this case, use the std::vector object instead of the cv::Mat object, and you can use the .push_back handle whenever you find a non-zero element that will dynamically resize the vector.

If you are trying to create a new image, you need to specify which image you want to see, because if you do not know how many unnecessary elements there are, how can you set the width and height? You can also get an odd number of items.

0
source share

All Articles