首页 > 解决方案 > RGB PCA图像的反向生成不起作用

问题描述

夏奇拉.jpg

我正在尝试压缩上面的图像,但我得到的输出是不正确的图像。我认为我正确地执行了 PCA 步骤,但在最后一步出现了问题。

夏奇拉压缩

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()

标签: pythonpca

解决方案


你搞砸了重塑。

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

  2. 替换img_inverse_reshaped = np.reshape(img_inverse, (930,620,3))img_inverse_reshaped = np.reshape(img_inverse, img.shape)

一旦我解决了这个问题,图像开始看起来或多或少是合理的。

然后你必须替换pca = PCA(.95)pca = PCA(n_components=3),图像看起来会更漂亮 =)


推荐阅读