RGB-PCA在图像上的实现

2024-09-29 00:14:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想实现PCA(主成分分析)以在图像上获得RGB版本。我正在打开github存储库中的图像。我在这里发现了一个非常有用的类似问题(Reverse generation of RGB PCA image not working) 并实施它,进行正确的纠正,但仍会出现错误:

line 22, in <module>
    img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))
AttributeError: 'JpegImageFile' object has no attribute 'shape'

这是我的密码:

from PIL import Image
import requests
from io import BytesIO
import pylab as plt
import numpy as np

#url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image1.jpg'
url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image2.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image3.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image4.jpg'
# url = 'https://raw.githubusercontent.com/TeoOG/Computer_Vision_Assistance/master/images/image5.jpg'

response = requests.get(url)
img = Image.open(BytesIO(response.content))



plt.axis('off')
plt.imshow(img)
img.show()

img_reshaped = np.reshape(img, (img.shape[0] * img.shape[1], img.shape[2]))
print(img_reshaped.shape)

from sklearn.decomposition import PCA

pca = PCA(n_components=3)
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, img.shape)

print(img_inverse.shape)

plt.axis('off')
plt.imshow(img_inverse_reshaped)
plt.show()

Tags: httpsimportcomurlimgrawpltcomputer