0

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()
martineau
  • 119,623
  • 25
  • 170
  • 301
DavidDunn
  • 143
  • 1
  • 12
  • Does this answer your question? [How to convert a PIL Image into a numpy array?](https://stackoverflow.com/questions/384759/how-to-convert-a-pil-image-into-a-numpy-array) – mkrieger1 Aug 04 '20 at 21:11
  • You need to convert `img` to a NumPy array. – mkrieger1 Aug 04 '20 at 21:12
  • okay the suggestion seem to work , only that I get a result mostly white , with some sparse , colored pixels . Not the result I need . Maybe something else also should be done – DavidDunn Aug 04 '20 at 21:25

0 Answers0