In this article we want to learn about Matplotlib Image Visualization, if you have worked with matplotlib, visualizing images are an important part of data analysis, computer vision and machine learning. Python provides different libraries for image visualization, and one of the most popular and powerful one is Matplotlib. In this article we want to talk about this concept.
First of all we need to import Python Matplotlib, and you can use pip for that.
1 |
pip install matplotlib |
For working with images using Matplotlib, we need to import the necessary libraries. In addition to Matplotlib pyplot module, we will also import the image module from the matplotlib library.
1 2 |
import matplotlib.pyplot as plt from matplotlib import image |
For visualizing an image, we need to load it into our Python code. Matplotlib provides the imread() function to read an image file. after that we can use the imshow() function to display the loaded image.
1 2 3 4 5 6 7 |
# Load the image img = image.imread('img.png') # Display the image plt.imshow(img) plt.axis('off') # Turn off the axis labels and ticks plt.show() |
Matplotlib offers different customization options to enhance the appearance of the displayed image. You can adjust the size, color and transparency of the image, as well as add titles, labels and annotations.
1 2 3 4 5 6 7 8 |
# Manipulate image properties plt.figure(figsize=(8, 6)) # Set the figure size plt.imshow(img, cmap='gray') # Set the color map to grayscale plt.title('Image Title') plt.xlabel('X Label') plt.ylabel('Y Label') plt.text(100, 100, 'Text Annotation', fontsize=12, color='red') # Add text annotation plt.show() |
If you want to save the visualized image, you can use the imsave() function from the image module.
1 |
image.imsave('path/to/save/image.png', img) |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import matplotlib.pyplot as plt from matplotlib import image # Load and Display an Image img = image.imread('matplotlib.png') plt.imshow(img) plt.axis('off') # Turn off the axis labels and ticks plt.show() # Manipulate Image Properties plt.figure(figsize=(8, 6)) plt.imshow(img, cmap='gray') plt.title('Image Title') plt.xlabel('X Label') plt.ylabel('Y Label') plt.text(100, 100, 'Text Annotation', fontsize=12, color='red') plt.show() # Save the Image image.imsave('path/to/save/image.png', img) |
Run the complete code and this will be the result
Learn More on Python Matplotlib
- Learn Python Matplotlib
- Data Visualization in Matplotlib
- How to Create Plotting Styles in Matplotlib
- How to Create Time Series in Matplotlib
- How to Customize Matplotlib Graphs
- How to Create Interactive Plots in Matplotlib
- Matplotlib Histogram
- 3D Plot in Matplotlib
- How to Create Subplots with Matplotlib
- Matplotlib Animation
Subscribe and Get Free Video Courses & Articles in your Email