opencv cv::solve() gives a wrong answers

Viewed 54

when I use opencv cv::solve() to solve a least-squares problems like get the x in Ax=b,I use like this:

cv::solve(A, B, coeff,cv::DECOMP_LU);

In my test example, A is a 6x6 mat, B is a 6x1 mat, coeff is the output 6x1 mat. All of the type is CV_64FC1 . When I use MATLAB func x = lscov(A,B) to solve it , the answer is different with the answer in opencv used cv::solve(). I don't know why and how to fix it.

This is my A mat:

       13650        2646        8281        1911        9261         546
        2646         546        1911         441        1911         126
        8281        1911       13650        2646        9261         546
        1911         441        2646         546        1911         126
        9261        1911        9261        1911        8281         441
         546         126         546         126         441          36

And this is my B mat

       10836
        2436
       14511
        2961
       10731
         666

When I use MATLAB I use like this

coeff = lscov(A,B);

The answer it gives is:

coeff =

    0.0000
    1.0000
   -0.0000
    6.0000
    0.0000
   -6.0000

When I use opencv cv::solve(), the answer it gives is:

[6.66296484815332e-17;
 -3.724946654716256;
 0.01073461162921725;
 0.0749237651372591;
 1.349984758490359;
 14.57495854564313]

It's strange and I don't know Why. Please tell me how to get the right answer.

1 Answers

Actually cv::solve is totally same with the matlab function lscov. I just believe that your implementation is wrong. You can find my implemented code below. When I tried the inputs with cv::solve function I got the coefficient output:

[-3.831204787688159e-15;
 1.000000000000029;
 4.557012826684974e-15;
 5.99999999999997;
 -9.7745995234962e-16;
 -5.999999999999993]

which can be rounded to:

    0.0000
    1.0000
   -0.0000
    6.0000
    0.0000
   -6.0000

Here is my code:

#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>


int main()
{
    double xx[6][6] = {{13650, 2646, 8281, 1911, 9261, 546},
                       {2646, 546, 1911, 441, 1911, 126},
                       {8281, 1911, 13650, 2646, 9261, 546},
                       {1911, 441, 2646, 546, 1911, 126},
                       {9261, 1911, 9261, 1911, 8281, 441},
                       {546, 126, 546, 126, 441, 36}};

    double yy[1][6] = {{10836,2436,14511,2961,10731,666}};





    cv::Mat img(cv::Size(6,6),CV_64F,xx);
    cv::Mat img2(cv::Size(1,6),CV_64F,yy);

    cv::Mat coeff;
    cv::solve(img,img2,coeff,cv::DECOMP_CHOLESKY);

    std::cout<<img<<std::endl;

    std::cout<<img2<<std::endl;

    std::cout<<std::endl;
    std::cout<<coeff<<std::endl;





}

Note: You can also find here my least square implemetation with the core algorithm I developed.

Related