How to Display Image in Python: Simple Methods Explained
To display an image in Python, you can use the
PIL library's Image.show() method or use matplotlib.pyplot.imshow() to show images inline. Both methods load the image file and open a window or plot to display it.Syntax
Here are two common ways to display images in Python:
- PIL (Pillow) method: Load an image with
Image.open('path')and display it withImage.show(). - Matplotlib method: Use
matplotlib.pyplot.imread('path')to read the image andimshow()to display it.
python
from PIL import Image # Load image img = Image.open('image.jpg') # Display image img.show()
Example
This example shows how to display an image using both PIL and matplotlib. It loads an image file named image.jpg and displays it in a window or plot.
python
from PIL import Image import matplotlib.pyplot as plt # Using PIL img = Image.open('image.jpg') img.show() # Using matplotlib img_data = plt.imread('image.jpg') plt.imshow(img_data) plt.axis('off') # Hide axes plt.show()
Output
Two windows open: one showing the image via PIL, another showing the image via matplotlib plot.
Common Pitfalls
Common mistakes when displaying images in Python include:
- Using a wrong file path or filename causes
FileNotFoundError. - For
Image.show(), the image opens in an external viewer which may not work in some environments like servers. - Matplotlib requires calling
plt.show()to actually display the image plot. - Not hiding axes in matplotlib can clutter the image display.
python
from PIL import Image # Wrong way: missing file or typo # img = Image.open('wrongname.jpg') # This raises FileNotFoundError # Right way: img = Image.open('image.jpg') img.show()
Quick Reference
| Method | Usage | Notes |
|---|---|---|
| PIL (Pillow) | Image.open('file').show() | Simple, opens external viewer |
| Matplotlib | plt.imshow(plt.imread('file')); plt.show() | Good for inline display in notebooks |
| File path | Use correct path to image file | Common source of errors |
Key Takeaways
Use PIL's Image.show() for quick external image display.
Use matplotlib's imshow() with plt.show() for inline image display in plots.
Always check the image file path to avoid errors.
Hide axes in matplotlib with plt.axis('off') for cleaner image display.