Ask Your Question

Subract one mat from another if a condition is met

asked 2016-02-22 16:12:12 -0600

willoughby gravatar image

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.

Thanks In Advance

edit retag flag offensive close merge delete


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

1 answer

Sort by ยป oldest newest most voted

answered 2016-02-23 05:38:08 -0600

updated 2016-02-23 05:41:34 -0600

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 (<float>(y,x) != 0)
          <float>(y,x) =<float>(y,x) -<float>(y,x); 
edit flag offensive delete link more


For the third scenario you can do

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


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

Of course!

Pedro Batista gravatar imagePedro Batista ( 2016-02-25 05:43:03 -0600 )edit

Question Tools

1 follower


Asked: 2016-02-22 16:12:12 -0600

Seen: 1,264 times

Last updated: Feb 23 '16