Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to multiply matrix in opencv java

Tags:

java

opencv

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);
like image 666
Rana Waleed Avatar asked Jun 30 '26 19:06

Rana Waleed


1 Answers

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]
like image 127
berak Avatar answered Jul 02 '26 07:07

berak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!