如何在 OpenCV 3 中使用 Python 中的 PCACompute 函数?

How to use the PCACompute function from Python in OpenCV 3?

cv2.PCACompute 函数在 OpenCV 2.4 中运行良好,语法如下:

import cv2
mean, eigvec = cv2.PCACompute(data)

该函数存在于 OpenCV 3.1 中,但会引发以下异常:

TypeError: Required argument 'mean' (pos 2) not found

C++ documentation 对解释我应该如何从 Python 调用它没有太大帮助。我猜 InputOutputArray 参数现在也是 Python 函数签名中的强制参数,但我无法找到使它们工作的方法。

有什么方法可以正确调用它吗?

(注意:我知道还有其他方法可以 运行 PCA,我可能会以其中之一结束。我只是好奇新的如何OpenCV 绑定有效。)

简单回答:

mean, eigvec = cv2.PCACompute(data, mean=None)

详情:

  1. 让搜索 PCACompute 源 first.Then 找到 this:

    // [modules/core/src/pca.cpp](L351-L360)
    void cv::PCACompute(InputArray data, InputOutputArray mean,
                        OutputArray eigenvectors, int maxComponents)
    {
        CV_INSTRUMENT_REGION()
    
        PCA pca;
        pca(data, mean, 0, maxComponents);
        pca.mean.copyTo(mean);
        pca.eigenvectors.copyTo(eigenvectors);
    }
    
  2. 好的,现在我们阅读 document:

    C++: PCA& PCA::operator()(InputArray data, InputArray mean, int flags, int maxComponents=0)
    Python: cv2.PCACompute(data[, mean[, eigenvectors[, maxComponents]]]) → mean, eigenvectors
    
    Parameters: 
        data – input samples stored as the matrix rows or as the matrix columns.
        mean – optional mean value; if the matrix is empty (noArray()), the mean is computed from the data.
    flags –
        operation flags; currently the parameter is only used to specify the data layout.
    
        CV_PCA_DATA_AS_ROW indicates that the input samples are stored as matrix rows.
        CV_PCA_DATA_AS_COL indicates that the input samples are stored as matrix columns.
    maxComponents – maximum number of components that PCA should retain; by default, all the components are retained.
    
  3. 这样说,

    ## py
    mean, eigvec = cv2.PCACompute(data, mean=None)
    

    等于

    // cpp 
    PCA pca;
    pca(data, mean=noArray(), flags=CV_PCA_DATA_AS_ROW);
    ...