Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Eigenvectors and eigenvalues in OpenCV

📅 2015-Jun-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, eigenvalue, eigenvector, opencv, pca ⬩ 📚 Archive

There are many libraries for C++ that can be used to compute Eigenvectors and Eigenvalues. However, if you are already using OpenCV in your project, then it can be used to get these values easily by using the PCA class. This class is declared in opencv2/core/core.hpp header file and defined in the modules/core/src/matmul.cpp source file.

Here is an example:

#include <opencv/cv.h>

// Input mat: 100 6-dimensional points
// Rows: 100 Cols: 6 Type: CV_F32
cv::Mat pt_mat;

cv::PCA pt_pca(pt_mat, cv::Mat(), CV_PCA_DATA_AS_ROW, 0);

// Mean
// Rows: 1 Cols: 6
cv::Mat pt_mean = pt_pca.mean;

// Eigen values
// In highest to lowest order
// Rows: 6 Cols: 1
cv::Mat pt_eig_vals = pt_pca.eigenvalues;

for (int i = 0; i < 6; ++i)
    std::cout << pt_eig_vals.at<float>(i, 0) << std::endl;

// Eigen vectors
cv::Mat pt_eig_vecs = pt_pca.eigenvectors;

Tried with: OpenCV 2.4.9 and Ubuntu 14.04