Search code examples
c++opencvmaskmat

OpenCV - absdiff with a mask


I am trying to calculate the absolute difference of two images using a mask so only a region of the images is considered in calculating the difference. But OpenCV does not have the mask part in its function. I saw this question but did not work for me. I am trying to multiply the result in the mask so that only the specified region remains.

code:

Mat region = //a grayscale image containing a region of 255 and the rest is zero
Mat img1, img2 = //two images of the same size as the region image and of type CV_8UC1
Mat mask = region / 255; //to make a binary mask
Mat difference = Mat::zeros(region .rows, region .cols, CV_8UC1);

cv::absdiff(img1, img2, difference);
difference = difference * mask;
if (!difference.empty()) imshow("difference", difference);

When I try this, I get an error.

error:

Error: Assertion failed (a_size.width == len) in cv::gemm

which happens here:

inline
Mat& Mat::operator = (const MatExpr& e)
{
    e.op->assign(e, *this);
    return *this;
}

Solution

  • difference * mask meaning that you are performing Matrix multiplication, in this case the height of difference must be the same as width of mask, if you want to perform an Element wise multiplication you should call difference.mul(mask)