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

时间:2017-10-30 13:34:40

标签: python opencv opencv3.1

使用以下语法,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绑定如何工作感到好奇。 )

1 个答案:

答案 0 :(得分:4)

简单回答:

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

详细信息:

  1. 首先搜索PCAC计算源。然后找到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);
    ...