Rana Waleed
Rana Waleed

Reputation: 55

Unable to multiply matrix in opencv java

I am new to Opencv in java. Problem is whenever i try to multiply two Mat type object of dimension (m x n) and (n x l) it gives the error.

OpenCV Error: Sizes of input arguments do not match (The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array') in cv::arithm_op, file ........\opencv\modules\core\src\arithm.cpp, line 1287 Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ........\opencv\modules\core\src\arithm.cpp:1287: error: (-209) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function cv::arithm_op ]

Here are my two matrices.

    Mat r = new Mat(2, 2, CvType.CV_32F);
    r.put(0, 0, 0.707);
    r.put(0, 1, -0.707);
    r.put(1, 0, 0.707);
    r.put(1, 1, 0.707);

    Mat mult = new Mat(1, 2, CvType.CV_32F);
    double d1 = 1.00;
    double d2 = 2.00;
    mult.put(0, 0, d1);
    mult.put(0, 1, d2);
    Mat final_mat = mult.mul(r);

Upvotes: 3

Views: 2127

Answers (1)

berak
berak

Reputation: 39796

Mat.mul() does a per element mutiplication (same as Core.multiply()), and both Mat's need to have the same dimensions for that.

what you obviously wanted, is the 'matrix multiplication'.

while this would be a simple mat*vec in c++, in java you have to use gemm for this:

Mat r = new Mat(2, 2, CvType.CV_32F);
r.put(0, 0, 0.707);
r.put(0, 1, -0.707);
r.put(1, 0, 0.707);
r.put(1, 1, 0.707);

Mat v = new Mat(1, 2, CvType.CV_32F);
double d1 = 1.00;
double d2 = 2.00;
v.put(0, 0, d1);
v.put(0, 1, d2);
Mat final_mat = new Mat();

Core.gemm(v,r,1,new Mat(),0,final_mat);

System.err.println(final_mat.dump());

[2.1210001, 0.70700002]

Upvotes: 6

Related Questions