Reverse generation of RGB PCA image not working

南笙酒味 提交于 2021-01-28 08:05:44

问题


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.

  1. replace img_reshaped = np.reshape(img, (930, 1860)) with img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))

  2. replace img_inverse_reshaped = np.reshape(img_inverse, (930,620,3)) with img_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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!