OpenCV 矩阵乘法断言在 class 内部失败,但在外部没有

OpenCV matrix multiplication assertion fail inside class, but not outside

试图避免使用 C 风格的结构并制作我的第一个 C++ class。不过有一个问题...

好的,所以我使用 OpenCv 定义了一个最小的 class 来显示我遇到的问题。 MatrixMathTest.cpp:

#include "MatrixMathTest.h"

MatrixMathTest::MatrixMathTest(){

    float temp_A[] = {1.0, 1.0, 0.0, 1.0};
    Mat A = Mat(2,2, CV_32F , temp_A);
    float temp_x[] = {3.0, 2.0};
    Mat x = Mat(2,1, CV_32F , temp_x);
}

void MatrixMathTest::doSomeMatrixCalcs(){
    x = A * x;    //expecting matrix mults, not element wise mults
    A = A.inv();  //proper matrix inversion
}

然后MatrixMathTest.h:

#include "opencv2/opencv.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;

class MatrixMathTest { 

public:                   
    MatrixMathTest();     
    void MatrixMathTest::doSomeMatrixCalcs(); 

private:
    Mat x;
    Mat A;
};

然后 运行 这个:

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "MatrixMathTest.h"

using namespace cv;
using namespace std;

void main(int argc, char** argv) {

    float temp_A[] = {1.0, 1.0, 0.0, 1.0};
    Mat A = Mat(2,2, CV_32F , temp_A);
    A = A.inv();
    cout << A << endl;

    float temp_x[] = {3, 2};
    Mat x = Mat(2,1, CV_32F , temp_x);
    x = A * x;
    cout << x << endl;

    MatrixMathTest tester;
    tester.doSomeMatrixCalcs();
}

main 中的相同代码将按预期工作,但一旦它进入 class,它就会失败:

如果我放置 A.inv();第一行我略有不同:

当我运行 直接在main 中以CV_32F 为类型的相同代码时没有断言失败。搜索该错误消息,shows people solving it by changing the variable types,但我已经尝试了断言提到的所有不同数字变量类型等等,它只是留在 CV_32F,因为这是我最后一次尝试。

我认为这与在 class 中有关? ??

但是什么?或者别的什么?

有些东西(非常基础?)我还没学会?

... 如果它与类型有关,如何调和最终对同一矩阵进行乘法和求逆的愿望 - 这些断言中的不同类型是否排除了这一点?

您正在屏蔽 MatrixMathTest::MatrixMathTest() 中的 class 变量 Ax。 由于您将它们声明为 Mat A = ...,那么您正在初始化这些 临时对象 ,而不是 class 的 成员对象 . 也就是说,当您 运行 和 doSomeMatrixCalcs() 时,您正在使用成员对象 this.Athis.x,但它们从未被初始化。因此它们包含错误数据,操作失败。

Mat A = ... 替换为 A = ...this.A = ...,事情应该会更好。

您的 class 构造函数隐藏了成员变量,请尝试这样做:

MatrixMathTest::MatrixMathTest(){

    float temp_A[] = {1.0, 1.0, 0.0, 1.0};
    A = Mat(2,2, CV_32F , temp_A);
    float temp_x[] = {3.0, 2.0};
    x = Mat(2,1, CV_32F , temp_x);
}

请注意,我已从 Ax 声明中删除了 Mat。因此,您之前创建的局部变量与 class 成员变量同名。然后当你调用 doSomeMatrixCalcs 时,它使用的成员变量未初始化,因此断言。