I'm trying to convert an image to grayscale and show it using pyplot. The steps I am taking are:
Step 1: Reading an image as input using Pillow in python
Step 2: Converting it into grayscale image using .convert('LA')
This is the code:
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open('28.jpg').convert('LA')
img.save('greyscale.png')
img=np.array(img)
print (img.shape)
plt.imshow(img)
Which outputs this as the shape of the np.array
:
(360, 480, 2)
The problem is when I try to view the output of this grayscale image using matplotlib.pyplot it throws the following error error:
TypeError Traceback (most recent call last)
<ipython-input-4-f6fac0acd82f> in <module>
1 img = np.array(img)
2 print (img.shape)
----> 3 plt.imshow(img)
~/.local/lib/python3.6/site-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs)
2697 filternorm=filternorm, filterrad=filterrad, imlim=imlim,
2698 resample=resample, url=url, **({"data": data} if data is not
-> 2699 None else {}), **kwargs)
2700 sci(__ret)
2701 return __ret
~/.local/lib/python3.6/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
~/.local/lib/python3.6/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs)
5492 resample=resample, **kwargs)
5493
-> 5494 im.set_data(X)
5495 im.set_alpha(alpha)
5496 if im.get_clip_path() is None:
~/.local/lib/python3.6/site-packages/matplotlib/image.py in set_data(self, A)
636 if not (self._A.ndim == 2
637 or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
--> 638 raise TypeError("Invalid dimensions for image data")
639
640 if self._A.ndim == 3:
TypeError: Invalid dimensions for image data
This is the image I am trying to read and convert it into grayscale 28.jpg