Python中的OpenCV PCA计算 [英] OpenCV PCA Compute in Python
问题描述
我正在通过OpenCV(在Python中)加载一组尺寸为128x128的测试图像,将它们重新整形为矢量(1、128x128),然后将它们全部放到一个矩阵中以计算PCA.我正在使用新的cv2库...
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...
代码:
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))
在PCA部分上它总是失败(我测试了图像加载,所有结果矩阵就是它应该的样子)...我得到的错误是:
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:
平均值,特征向量= cv.PCACompute(matrix_test,np.mean(matri_test,axis = 0))
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:错误:(-215)_mean.size()==函数操作符()中的mean_sz
cv2.error: /path/to/OpenCV-2.3.1/modules/core/src/matmul.cpp:2781: error: (-215) _mean.size() == mean_sz in function operator()
推荐答案
我认为问题在于
np.mean(matrix_test, axis=0)
它的大小是(128x128),而不是(1,128x128).因此,下面的代码应该可以工作
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))
这篇关于Python中的OpenCV PCA计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!