I want to implement PCA (Principal Component Analysis) to get an RGB version on an image . I'm opening the images from a github repository . I found a very helpful similar question here (Reverse generation of RGB PCA image not working) and implement it , with the right corrections , but still getting the error:
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'
Here's my code :
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()