OpenCV PCA Compute in Python

I upload a set of test images via OpenCV (in Python) 128x128 in size, rearranging them into vectors (1, 128x128) and putting them all together in a matrix for PCA calculation. I am using new cv2 libraries ...

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 all this fails in the PCA part (I tested the image loading and everything, the resulting matrix - how it should be) ... the error I get:

File "main.py", line 22,

means 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 the operator () function

+8
python opencv pca
source share
2 answers

I think the problem is related to size

 np.mean(matrix_test, axis=0) 

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

 mean, eigenvectors = cv.PCACompute(matrix_test, np.mean(matrix_test, axis=0).reshape(1,-1)) 
+7
source share

You can also install

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

and the function calculates the average value.

+5
source share

All Articles