python - RGB图像的PCA

标签 python numpy pca svd

我正在尝试弄清楚如何使用 PCA 在 Python 中对 RGB 图像去相关。 我正在使用 O'Reilly Computer vision 书中的代码:

from PIL import Image
from numpy import *

def pca(X):
  # Principal Component Analysis
  # input: X, matrix with training data as flattened arrays in rows
  # return: projection matrix (with important dimensions first),
  # variance and mean

  #get dimensions
  num_data,dim = X.shape

  #center data
  mean_X = X.mean(axis=0)
  for i in range(num_data):
      X[i] -= mean_X

  if dim>100:
      print 'PCA - compact trick used'
      M = dot(X,X.T) #covariance matrix
      e,EV = linalg.eigh(M) #eigenvalues and eigenvectors
      tmp = dot(X.T,EV).T #this is the compact trick
      V = tmp[::-1] #reverse since last eigenvectors are the ones we want
      S = sqrt(e)[::-1] #reverse since eigenvalues are in increasing order
  else:
      print 'PCA - SVD used'
      U,S,V = linalg.svd(X)
      V = V[:num_data] #only makes sense to return the first num_data

   #return the projection matrix, the variance and the mean
   return V,S,mean_X

我知道我需要展平我的图像,但形状是 512x512x3。 3 的维度会影响我的结果吗?我该如何截断这个? 我如何找到保留多少信息的数量?

最佳答案

如果有三个波段(RGB 图像就是这种情况),您需要像这样 reshape 图像

X = X.reshape(-1, 3)

对于 512x512 图像,新的 X 的形状为 (262144, 3)。 3 的维度不会影响您的结果;该维度表示图像数据空间中的特征。 X 的每一行都是一个样本/观察值,每一列代表一个变量/特征。

图像中的方差总量等于np.sum(S),即特征值之和。您保留的方差量将取决于您保留的特征值/特征向量。所以如果你只保留第一个特征值/特征向量,那么你保留的图像方差分数将等于

f = S[0] / np.sum(S)

关于python - RGB图像的PCA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533392/

相关文章:

python - 从 Python 集合中删除已更改的对象

python - matplotlib 自定义线条颜色和线型循环器

python - 给定矩阵列表,对它们求和但忽略某些矩阵的行

r - 在 R 中对非常大的数据集进行 PCA

python - 使用 Tumblr API 安排帖子

python - tensorflow 。将张量的未知维度大小转换为 int

python 3 : Multiply a vector by a matrix without NumPy

python - 是什么导致 numpy.nanstd() 返回 nan?

使用 PCL 时私有(private)函数的 C++ 继承

python - KNN 模型(使用 PCA)在 k 的每次迭代中输出相同的精度