OpenCV - 带有掩码的 absdiff

OpenCV - absdiff with a mask

我正在尝试使用蒙版计算两个图像的绝对差异,因此在计算差异时只考虑图像的一个区域。但是 OpenCV 在 its function. I saw this question 中没有掩码部分,但对我不起作用。我正在尝试将蒙版中的结果相乘,以便只保留指定的区域。

代码:

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

当我尝试这个时,出现错误。

错误:

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

发生在这里:

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

difference * mask 表示您正在执行 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 您应该调用 difference.mul(mask)