1

Shakira.jpg

I am trying to compress the above image but the output that I am getting is an improper image. I think I am doing the PCA steps correctly, but something is going wrong at the final step.

Shakira compressed

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()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Zing
  • 83
  • 1
  • 8

1 Answers1

0

You have messed up the reshape.

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

  2. replace img_inverse_reshaped = np.reshape(img_inverse, (930,620,3)) with img_inverse_reshaped = np.reshape(img_inverse, img.shape)

Once I fixed that, the image started to look more or less reasonable.

Then you have to replace pca = PCA(.95) to pca = PCA(n_components=3), and the image will look even pretty =)

lenik
  • 23,228
  • 4
  • 34
  • 43
  • Thanks. I figured out the error in my code as well. If I divide img_inverse_reshaped by 255, the problem gets fixed. Yes, n_components=3 looks pretty :) – Zing Jul 29 '18 at 16:32