如何在 OpenCV 中计算矩阵秩?

How to calculate matrix rank in OpenCV?

我在 OpenCV 中有一个非方阵。 我想计算它的排名。 我知道您需要进行 SVD 分解并计算行数或其中的一部分?不确定... 我真的可以在 OpenCV(C/C++) 中使用代码示例,因为我犯错误的空间太大了...... 我找到了这个帖子... opencv calculate matrix rank

但是没有代码示例...

所以,如果没有代码示例,也许您可​​以解释一下在 OpenCV 中查找非方矩阵秩的步骤?

here所述,您需要找到非零奇异值的个数。所以,首先用SVD分解找到奇异值,然后统计非零值的个数。您可能需要应用一个小阈值来解决数字错误:

#include <opencv2\opencv.hpp>
using namespace cv;

int main()
{
    // Your matrix
    Mat1d M = (Mat1d(4,5) <<    1, 0, 0, 0, 2, 
                                0, 0, 3, 0, 0, 
                                0, 0, 0, 0, 0, 
                                0, 2, 0, 0, 0);

    // Compute SVD
    Mat1d w, u, vt;
    SVD::compute(M, w, u, vt);

    // w is the matrix of singular values
    // Find non zero singular values.

    // Use a small threshold to account for numeric errors
    Mat1b nonZeroSingularValues = w > 0.0001;

    // Count the number of non zero
    int rank = countNonZero(nonZeroSingularValues);

    return 0;
}