2011-12-19 247 views
8

我正在通過OpenCV(Python中)加載一組尺寸爲128x128的測試圖像,將它們重新整形爲矢量(1,128x128),並將它們放在矩陣中以計算PCA。我使用的是新CV2 libaries ...OpenCV PCA在Python中計算

代碼:

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部分(我所測試的圖像加載和一切,結果矩陣是應該的)......我得到的錯誤是:

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()

回答

7

我認爲這個問題是

np.mean(matrix_test, axis=0) 

其規模的大小是(128x128),而不是(1,128x128)。因此下面的代碼應該工作

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

這樣做的伎倆......完全錯過了這樣一個愚蠢的錯誤!謝謝! – Veles 2011-12-19 23:44:30

5

你也可以把

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

和函數計算的平均值。

+0

好的答案+1這對我有很大的幫助。我也發現'mean = None',就等於這個解決方案。乾杯 – DarkCygnus 2017-12-05 19:08:01