OpenCV Q&A Forum - RSS feedhttp://answers.opencv.org/questions/OpenCV answersenCopyright <a href="http://www.opencv.org">OpenCV foundation</a>, 2012-2018.Mon, 18 Nov 2013 10:53:16 -0600How to get values of a Matrix which are non zerohttp://answers.opencv.org/question/24076/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???Mon, 18 Nov 2013 05:51:33 -0600http://answers.opencv.org/question/24076/how-to-get-values-of-a-matrix-which-are-non-zero/Answer by Pedro Batista for <p>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. </p>
<p>My matlab code is:</p>
<pre><code> 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
</code></pre>
<p>The c++ translation that I have now is:</p>
<pre><code>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
}
</code></pre>
<p>So, how can I create a matrix which only has the values that the mask satisfies???</p>
http://answers.opencv.org/question/24076/how-to-get-values-of-a-matrix-which-are-non-zero/?answer=24090#post-id-24090The 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.Mon, 18 Nov 2013 10:53:16 -0600http://answers.opencv.org/question/24076/how-to-get-values-of-a-matrix-which-are-non-zero/?answer=24090#post-id-24090