【问题标题】:How to use the PCACompute function from Python in OpenCV 3?如何在 OpenCV 3 中使用 Python 中的 PCACompute 函数?
【发布时间】:2017-10-31 13:16:55
【问题描述】:

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 绑定是如何工作的。)

【问题讨论】:

  • 如果有帮助,有一个旧的 question 与您面临的这个问题相似,给出了相同(和其他)的解决方案。

标签: python opencv opencv3.1


【解决方案1】:

简单回答:

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

详细说明:

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

【讨论】:

  • 谢谢,您必须通过 None 的事实在文档中一点也不明显,即使是关于 noArray() 的文档也是如此:)
  • 文档上写着mean – optional mean value; if the matrix is empty (noArray()), the mean is computed from the data. 所以,直接通过None。
猜你喜欢
  • 1970-01-01
  • 2013-02-03
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多