【发布时间】:2020-11-03 14:16:00
【问题描述】:
我有一个 RGB 图像。我想应用 PCA 进行图像压缩,并在应用后查看输出。
这是我尝试做的:
from PIL import Image
import numpy as np
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
------
def load_image(infilename):
img = Image.open(infilename)
img.load()
img.show()
data = np.asarray(img, dtype="int32")
return data
---------
data = load_image("Image_for_pca.jpg")
r = data[:,:,0]
print("r", r.shape)
g = data[:,:,1]
print("g", g.shape)
b = data[:,:,2]
print("b", b.shape)
concat_matrix_image = np.hstack((np.hstack((r,g)),b))
print("concatMatrixImage", concat_matrix_image.shape)
output of the prints:
r (161, 212)
g (161, 212)
b (161, 212)
concatMatrixImage (161, 636)
# list of dimension
pca_number_of_wanted_dimension = [3 ,5 ,10 ,15 ,20 ,30]
-------
def create_pca_model(number_of_components):
pca = PCA(n_components=number_of_components)
return pca
-------
def plot_varience_on_pca(pca):
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.title("The number of wanted dimension is {}".format(pca.n_components))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance')
plt.show()
------
def recover_pic(pca, principal_components):
#Project lower dimension data onto original features
approximation = pca.inverse_transform(principal_components)
approximation = approximation.reshape(-1,161,212)
# approximation = approximation.astype(np.uint8)
# print(approximation.shape)
# img = Image.fromarray(approximation, 'RGB')
approximation.show()
-------
for i in pca_number_of_wanted_dimension:
pca = create_pca_model(i)
principal_components = pca.fit_transform(concat_matrix_image)
print(principal_components.shape)
recover_pic(pca, principal_components)
plot_varience_on_pca(pca)
pca.inverse_transform之后如何恢复图片?
【问题讨论】:
标签: python scikit-learn pca