How to get values of a Matrix which are non zero

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???


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!


OpenCv does support Matrix Expresions like A > B or A <= B and so on.

This is stated in the Documentation off cv::Mat


If you're simply wanting to store values, the Mat object is probably not the best way, since it has been made for the purpose of containing images.

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

If you're trying to create a new image, then you have to be specific about what kind of image you want to see, because if you don't know how many nonzero elements there are, how can you set the width and height? Also you might end up with an odd number of elements.

链接地址: http://www.djcxy.com/p/75554.html

上一篇: 可逆状态monad(和解析器)

下一篇: 如何获得非零矩阵的值