41

I have two Mat images in OpenCV:

Mat ft = Mat::zeros(src.rows,src.cols,CV_32FC1);
Mat h = Mat::zeros(src.rows,src.cols,CV_32FC1);

Both images are the same dimension and are calculated from a single source image.

I would like to multiply these two images but have tried using both

Mat multiply1 = h*ft;

Mat multiply2;
gemm(h,ft,1,NULL,0,multiply2);

but both result in the following assertion failure:

OpenCV Error: Assertion failed (a_size.width == len) in unknown function, file ...matmul.cpp Termination called after throwing 'cv::exception'

What am I doing wrong?

1
  • 1
    To see what the exception actually says, put the failing line inside a try block like: try { [...] } catch (cv::Exception const & e) { std::cerr<<"OpenCV exception: "<<e.what()<<std::endl; } Commented Nov 11, 2012 at 19:59

1 Answer 1

134

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a × b] with matrix B of size [b × c] to produce matrix C of size [a × c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);
5
  • Sorry, but I fail to see how this answers the question. Why should the assertion fail in the first statement "h*ft"?
    – Devesh
    Commented Mar 5, 2014 at 10:21
  • 6
    Because as it stands, h*ft is attempting to perform matrix multiplication which, noticing how h and ft are formed, would require src.rows == src.cols.
    – Chris
    Commented Mar 5, 2014 at 11:17
  • Oh yeah, of course. I assumed they were equal. My bad.
    – Devesh
    Commented Mar 5, 2014 at 11:20
  • 4
    The * operator is not supported in JAVA. You have to use the Core.gemm method.
    – sbaechler
    Commented Apr 8, 2014 at 18:47
  • 1
    This is very helpful! Thanks @Chris for the explanation.
    – atereshkov
    Commented May 10, 2018 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.