OpenCV Mat cpp operation only on condition

Question:

Having a hard time figuring out how to do this python operation in c++ without looping.

The goal is to perform an operation only on a part of the cv::Mat that meets a condition.

In this case, scaling values of the image that were originally between -5 and 5..

image[-5<image<5] = image[-5<image<5]*2+1
Asked By: Alberto MQ

||

Answers:

There is no direct conversion between NumPy and OpenCV (C++).
We may use a mask, and get a syntax that looks "vectorized":

cv::Mat mask = (image > (-5)) & (image < 5);
cv::copyTo(image*2+1, image, mask);

  • cv::Mat mask = (image > (-5)) & (image < 5);
    Creates a mask with 255 where conditions are true, and 0 where false.
  • cv::copyTo(image*2+1, image, mask);
    Copy the values image*2+1 to image, only in pixels where mask != 0.

More compact implementation:

cv::copyTo(image*2+1, image, (image > (-5)) & (image < 5));

Note about efficiency:
The above example is probably less efficient then using for loops.
The purpose is to solve it in a syntax that is closer to NumPy (assuming you prefer code that resembles NumPy [or more compact] over efficiency).
In case you care about efficiency, using for loops, is probably better solution.

Answered By: Rotem
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.