how to show an image after pca?
I have a RGB image. I want to apply PCA for image-compression and see the output after the application.
Here’s what I tried to do:
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)
How to recover the picture after the pca.inverse_transform
?