问题
Shakira.jpg
I am trying to compress the above image but the output that I am getting is an improper image. I think I am doing the PCA steps correctly, but something is going wrong at the final step.
Shakira compressed
import pylab as plt
import numpy as np
img = plt.imread("shakira.jpg")
print(img.shape)
plt.axis('off')
plt.imshow(img)
plt.show()
img_reshaped = np.reshape(img, (930, 1860))
print(img_reshaped.shape)
from sklearn.decomposition import PCA
pca = PCA(.95)
pca.fit(img_reshaped)
img_transformed = pca.transform(img_reshaped)
print(img_transformed.shape)
img_inverse = pca.inverse_transform(img_transformed)
print(img_inverse.shape)
plt.imshow(img_inverse)
plt.show()
img_inverse_reshaped = np.reshape(img_inverse, (930,620,3))
print(img_inverse.shape)
plt.axis('off')
plt.imshow(img_inverse_reshaped)
plt.show()
回答1:
You have messed up the reshape.
replace
img_reshaped = np.reshape(img, (930, 1860))
withimg_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))
replace
img_inverse_reshaped = np.reshape(img_inverse, (930,620,3))
withimg_inverse_reshaped = np.reshape(img_inverse, img.shape)
Once I fixed that, the image started to look more or less reasonable.
Then you have to replace pca = PCA(.95)
to pca = PCA(n_components=3)
, and the image will look even pretty =)
来源:https://stackoverflow.com/questions/51580996/reverse-generation-of-rgb-pca-image-not-working