Skip to content

Instantly share code, notes, and snippets.

@3100
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3100/067b79489dbf75ab8f8f to your computer and use it in GitHub Desktop.
Save 3100/067b79489dbf75ab8f8f to your computer and use it in GitHub Desktop.
主成分分析でn次元に縮小させた結果から画像を復元してみる
from sklearn.decomposition import PCA
from PIL import Image
import numpy as np
import scipy as sp
if __name__ == '__main__':
# 画像ファイル名に変えてください
filePath = 'gs.jpg'
# 試行するnの組(画像ピクセルサイズの最大数を超えないこと)
ns = [1,2,5,10,50,100,250]
imgAry = np.asarray(Image.open(filePath).convert('L'))
for n in ns:
pca = PCA(n_components=n)
pca.fit(imgAry)
pca_res = pca.transform(imgAry)
restored = pca.inverse_transform(pca_res)
print sum(pca.explained_variance_ratio_)
sp.misc.imsave('result' + str(n) + '.png', restored)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment