Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV PCA Compute in Python

Tags:

python

opencv

pca

I'm loading a set of test images via OpenCV (in Python) which are 128x128 in size, reshape them into vectors (1, 128x128) and put them all together in a matrix to calculate PCA. I'm using the new cv2 libaries...

The code:

import os
import cv2 as cv
import numpy as np

matrix_test = None
for image in os.listdir('path_to_dir'):
    imgraw = cv.imread(os.path.join('path_to_dir', image), 0)
    imgvector = imgraw.reshape(128*128)
    try:
        matrix_test = np.vstack((matrix_test, imgvector))
    except:
        matrix_test = imgvector

# PCA
mean, eigenvectors = cv.PCACompute(matrix_test, np.mean(matrix_test, axis=0))

And it allways fails on the PCA part (I tested the image loading and all, the resulting matrix is how it should be)...the error I get is:

File "main.py", line 22, in

mean, eigenvectors = cv.PCACompute(matrix_test, np.mean(matri_test, axis=0))

cv2.error: /path/to/OpenCV-2.3.1/modules/core/src/matmul.cpp:2781: error: (-215) _mean.size() == mean_sz in function operator()

like image 827
Veles Avatar asked Dec 19 '11 21:12

Veles


People also ask

How does Python implement PCA?

Performing PCA using Scikit-Learn is a two-step process: Initialize the PCA class by passing the number of components to the constructor. Call the fit and then transform methods by passing the feature set to these methods. The transform method returns the specified number of principal components.


2 Answers

I think the problem is with the size of

np.mean(matrix_test, axis=0)

Its size is (128x128,) and not (1, 128x128). Thus the code below should work

mean, eigenvectors = cv.PCACompute(matrix_test, np.mean(matrix_test, axis=0).reshape(1,-1))
like image 116
Dat Chu Avatar answered Oct 15 '22 09:10

Dat Chu


You can also put

cv.PCACompute(matrix_test, mean = np.array([]))

and the function computes the mean.

like image 34
Tomas Avatar answered Oct 15 '22 09:10

Tomas