# Subract one mat from another if a condition is met

I have 2 matrices of the same size. One of which has a "black area" where all the values are Scalar(0,0,0). I want to subtract the other matrix from this one but only in places where it isn't black (I want to leave the black alone). Id prefer not to iterate over the entire matrix if possible. I believe this is done using a mask but I am unclear how to set that up.

edit retag close merge delete

( 2016-02-22 16:19:53 -0600 )edit

Sort by ยป oldest newest most voted

Case 1: Mat is of type unsigned char/short (most of cases)

Plain subtracting will work, since values will not go lower than 0 anyway.

cv::Mat A, B, C;

C = A - B;


Case 2: Mat is of type signed char/short or float/double...

...but negative values on result Mat may be set to zero

cv::Mat A, B, C;

C = A - B; // this Mat will have some negative values.

C.setTo(0, C < 0); // Negative values (and previous 0 values) will be set to 0.


...and negative values on result Mat are acceptable, only original 0 values can't be negative

If this is the scenario, you're left with no other option but iterate through all the pixels

cv::Mat A, B, C;

for (int x = 0; n < A.cols; n++)
{
for (int y = 0; y < A.rows; i++)
{
if (A.at<float>(y,x) != 0)
C.at<float>(y,x) = A.at<float>(y,x) - B.at<float>(y,x);
}
}

more

For the third scenario you can do

cv::Mat A, B, C;
C = A - B; // this Mat will have some negative values.
C.setTo(0,A==0);


guy

( 2016-02-24 16:29:37 -0600 )edit

Of course!

( 2016-02-25 05:43:03 -0600 )edit

Official site

GitHub

Wiki

Documentation