You can easily convert this MATLAB code:
idx = A > 0; B(idx) = 0; // same as B(A>0) = 0;
in opencv like:
Mat1d A(...) Mat1d B(...) Mat1b idx = A > 0; B.setTo(0, idx) = 0;
As for performance, in C ++ it is usually faster (depending on the allowed optimizations) working on raw pointers (but less readable):
for (int r = 0; r < B.rows; ++r) { double* pA = A.ptr<double>(r); double* pB = B.ptr<double>(r); for (int c = 0; c < B.cols; ++c) { if (pA[c] > 0.0) pB[c] = 0.0; } }
Also note that there is no logical matrix in OpenCV, but it is a CV_8UC1 matrix (aka single-channel matrix unsigned char ), where 0 means false , and any value >0 (usually 255 ).
Rating
Please note that this may vary according to the optimization included in OpenCV. You can check the code below on your PC to get accurate results.
Time in ms:
my results my results @AdrienDescamps (OpenCV 3.0 No IPP) (OpenCV 2.4.9) Matlab : 13.473 C++ Mask: 640.824 5.81815 ~5 C++ Loop: 5.24414 4.95127 ~4
Note. I'm not quite sure about performance degradation with OpenCV 3.0, so I just notice: check the code below on your PC to get accurate results.
Like @AdrienDescamps in the comments:
It seems that the drop in performance with OpenCV 3.0 is due to the OpenCL option, which is now included in the comparison operator.
C ++ code
#include <opencv2/opencv.hpp>
Matlab Code
% Random initialize A with values in [-100, 100] A = (rand(1000) * 200) - 100; % B initialized with some constant (5) value B = ones(1000) * 5; tic B(A>0) = 0; toc
UPDATE
OpenCV 3.0 uses IPP optimization in the setTo function. If you have this (you can check with cv::getBuildInformation() ), you will get a faster calculation.