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
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.
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
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 with255
where conditions are true, and 0 where false.cv::copyTo(image*2+1, image, mask);
Copy the valuesimage*2+1
toimage
, only in pixels wheremask
!=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.