0

I would like to do the following operation (which is at the current state in Matlab) using cv::Mat variables.

I have matrix mask:

mask =

 1     0     0
 1     0     1

then matrix M:

M =

 1
 2
 3
 4
 5
 6
 3

and samples = M(mask,:)

samples =

 1
 2
 6

My question is, how can I perform the same operation like, M(mask,:), with OpenCV?

Kristan
  • 387
  • 6
  • 19
  • I guess that `mask` and `M` are matrix but what would be the type of `samples` ? – Gabriel Devillers Aug 15 '17 at 10:50
  • @Gabriel Devillers that would be matrix (cv::Mat) as well. The above presented example is just given with random numbers and sizes, but keeping the same meaning for the real task. – Kristan Aug 15 '17 at 10:53

1 Answers1

1

With my knowledge the closet function to this thing is copyTo function in opencv that get matrix and mask for inputs. but this function hold original structure of your matrix you can test it.

I think there is no problem to use for loop in opencv(in c++) because it's fast. I propose to use for loop with below codes.

Mat M=(Mat_<uchar>(2,3)<<1,2,3,4,5,6); //Create M
cout<<M<<endl;

Mat mask=(Mat_<bool>(2,3)<<1,0,0,1,0,1); // Create mask
cout<<mask<<endl;

Mat samples;
///////////////////////////////
for(int i=0;i<M.total();i++)
{
    if(mask.at<uchar>(i))
        samples.push_back(M.at<uchar>(i));
}
cout<<samples<<endl;

above code result below outputs.

[  1,   2,   3;
   4,   5,   6]

[  1,   0,   0;
   1,   0,   1]

[  1;
   4;
   6]

with using copyTo your output will be like below

[1 0 0
 4 0 6];

enter image description here

Saeed Masoomi
  • 1,703
  • 1
  • 19
  • 33