python - 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()
解决方案
你搞砸了重塑。
替换
img_reshaped = np.reshape(img, (930, 1860))
为img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[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)
,图像看起来会更漂亮 =)
推荐阅读
- python - 为什么我在解密程序中收到有关字符串的错误?
- python-3.x - aws 胶水主要丢弃空字段
- javascript - JavaScript:将对象属性中的每个单词缩短为固定长度?
- mysql - 当我添加表中已存在的产品时,数量值未在数据库中更新
- intellij-idea - 我可以为 IntelliJ 中的 Project Pane -> Changed Files 视图使用模块结构(折叠 Java 包路径)吗?
- mysql - Count(*) 按月分组,如果月计数为 0,则值为 0
- ruby-on-rails - Rails 5.2 简单更新方法的语法错误
- windows - 静态构建中缺少 Qt 应用程序资源
- php - 在 wp_query 中分别列出每个自定义帖子类型,而不重复循环
- javascript - 如何防止内容在初始页面加载时被移动浏览器的状态栏向上推送和隐藏?