Ask Your Question

Revision history [back]

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 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 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); 
            }
        }

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 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 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) C.at<float>(y,x) = A.at<float>(y,x) - B.at<float>(y,x); 
            }
        }

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); 
            }
        }