How to Display an Image as Grayscale in Python Matplotlib?

How to Display an Image as Grayscale in Python Matplotlib?

You can convert a given image to a grayscale image using four simple steps:

  1. Import the PIL and Matplotlib libraries
  2. Open the image with PIL.Image.open(filename).
  3. Convert the opened image to grayscale using img.convert("L") with greyscale mode “L”.
  4. Display the image using Matplotlib’s plt.imshow(gray_img, cmap='gray') function.

Here’s the minimal code to convert any given .jpg image to a grayscale image:

import PIL
import matplotlib.pyplot as plt

img = PIL.Image.open("pic.jpg")
gray_img = img.convert("L")
plt.imshow(gray_img, cmap='gray')

Now, you may wonder:

How to Save a Grayscale Image with Matplotlib?

💡 To save the grayscale image generated by Matplotlib’s plt.imshow(), add another line plt.savefig("gray.jpg"). This takes the shown grayscale image and saves it in the file "gray.jpg".

Here’s the code with the additional line highlighted:

import PIL
import matplotlib.pyplot as plt

img = PIL.Image.open("pic.jpg")
gray_img = img.convert("L")
plt.imshow(gray_img, cmap='gray')
plt.savefig("gray_pic.jpg")

You may wonder where Matplotlib’s plt.savefig() function takes the image to be saved—you only pass the outfile path name as a string but no explicit image to be saved! The reason is that Matplotlib’s plt object works like a state machine. If you call plt.savefig(path) it takes the lastly generated figure and saves it at the given path.

Try It in Our Interactive Jupyter Notebook

If you’re like me, you want to try things quickly. To help you do this, I’ve set up an interactive Jupyter notebook so that you can execute this in your own browser:

How to Display an Image as Grayscale in Python Matplotlib?
Interactive Code Example

Just click on the code to try it in a new tab.


If you really want to dive into Matplotlib, check out our in-depth academy course here:

It’s one of the most in-depth Matplotlib courses in the web—and it’ll boost your data science and data visualization skills to a level that’ll impress your colleagues. Check it out, it’s very inexpensive! 🙂