简体   繁体   中英

Matrix masking operation in OpenCV(C++) and in Matlab

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?

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];

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM