How to Display an Image as Grayscale in Python Matplotlib?
You can convert a given image to a grayscale image using four simple steps:
- Import the PIL and Matplotlib libraries
- Open the image with
- Convert the opened image to grayscale using
img.convert("L")with greyscale mode “L”.
- Display the image using Matplotlib’s
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
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
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:
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! 🙂
💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.
- Question: Why do Java programmers wear glasses?
- Answer: Because they cannot C# …!
Feel free to check out our blog article with more coding jokes. 😉
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.