Skip to content
How to Plot Images with Matplotlib in Python

Mastering Image Processing with Matplotlib in Python: A Comprehensive Guide

In the realm of data science, the significance of data visualization is unparalleled. One such powerful tool in the Python ecosystem is Matplotlib. This library is a versatile tool for crafting static, animated, and interactive visualizations in Python. But did you know that Matplotlib can also be a potent tool for image processing?

You might be asking, "What's image processing?" It's a method of performing operations on images, such as analyzing, modifying, and interpreting their features. These operations often involve NumPy arrays, which are a fundamental data structure in Python used for storing and manipulating numerical data.

Want to quickly create Data Visualization from Python Pandas Dataframe with No code?

PyGWalker is a Python library for Exploratory Data Analysis with Visualization. PyGWalker (opens in a new tab) can simplify your Jupyter Notebook data analysis and data visualization workflow, by turning your pandas dataframe (and polars dataframe) into a Tableau-style User Interface for visual exploration.

PyGWalker for Data visualization (opens in a new tab)

Matplotlib: Unveiling the Magic of Images

At its core, an image is nothing more than a multidimensional NumPy array, where each pixel corresponds to a specific array element. These pixels have a numerical value, typically ranging from 0 (black) to 255 (white) for a grayscale image. On the other hand, a color image, or an RGB image, has three such arrays corresponding to the Red, Green, and Blue channels. There's also an RGBA format, which includes an additional Alpha channel for transparency.

Matplotlib's magic truly comes alive when working with these images. By manipulating these NumPy arrays, you can perform various image processing tasks, such as image modification, image cropping, image scaling, image rotation, and more.

For instance, consider you want to convert an RGB image into a grayscale image. This task involves averaging the values in the red, green, and blue channels for each pixel. Sounds complex? With Matplotlib, it's as easy as pie! Check out our guide on ChatGPT Code Interpreter for Data Science for more on this.

Plotting Your Way Through Images

Plotting image data is where Matplotlib truly shines. It provides an extensive collection of functions for displaying images, creating histogram plots, and even image segmentation. Moreover, it allows you to customize these plots in a multitude of ways.

One such customization is the color scale, which is a graphical representation of color gradations. In Matplotlib, you can adjust the color scale of an image to represent different features more prominently. For instance, you could highlight certain areas of an image or enhance the contrast.

The color scale also plays a crucial role. For an RGB image, each pixel is represented as three intensity values (Red, Green, Blue). Thus, it is represented as a 3D NumPy array.

# Create a random RGB image
image_rgb = np.random.randint(0, 256, (512, 512, 3), dtype=np.uint8)
# Display the RGB image

Performing Operations on Images

Matplotlib provides numerous functionalities to perform operations on these images.

For example, image modification can be as simple as adjusting the pixel intensity values.

# Increase intensity of all pixels by 50
image_mod = image + 50
# Display the modified image
plt.imshow(image_mod, cmap='gray')

You can also perform operations like image cropping, image scaling, and image rotation.

# Crop the image to 256x256
image_crop = image[:256, :256]
# Display the cropped image
plt.imshow(image_crop, cmap='gray')

Image Visualization with Matplotlib

Beyond simple image display, Matplotlib provides comprehensive tools for image visualization. It allows you to plot histogram plots, apply color scales, and even perform image segmentation.

For instance, you can plot the histogram of pixel intensities in an image.

# Plot histogram of pixel intensities
plt.hist(image.ravel(), bins=256, color='gray', alpha=0.7)

You can also remove axes and add a color scale to the image.

# Display the image with a color scale and no axes
plt.imshow(image, cmap='gray')

With a good understanding of these fundamentals, you'll be ready to dive into more advanced topics like image filtering, and displaying multiple images. You might also want to explore how Matplotlib integrates with data visualization tools like RATH (opens in a new tab), Tableau, and Chartio.

Advanced Image Processing Techniques

Armed with the basics, we can now explore more intricate image processing techniques.

Image filtering is a method used to modify or enhance an image. For example, a common application of image filtering is smoothing or blurring an image. In Matplotlib, this can be achieved using convolution with a filter kernel.

from scipy.ndimage import gaussian_filter
# Apply Gaussian filter for image smoothing
image_smooth = gaussian_filter(image, sigma=1)
# Display the filtered image
plt.imshow(image_smooth, cmap='gray')

Likewise, image rotation is an essential operation, especially in tasks such as data augmentation. Thankfully, it's a cakewalk with Matplotlib.

from scipy.ndimage import rotate
# Rotate the image by 45 degrees
image_rotated = rotate(image, angle=45)
# Display the rotated image
plt.imshow(image_rotated, cmap='gray')

Another exciting application is image segmentation, the process of partitioning an image into multiple segments or 'regions of interest'. This technique is quite useful in tasks such as object detection or image recognition.

from skimage.segmentation import slic
from skimage.color import label2rgb
# Apply SLIC segmentation
segments = slic(image_rgb)
# Display the segmentation
segmented_image = label2rgb(segments, image_rgb, kind='avg')

Finally, displaying multiple images (also known as subplotting) is a fantastic way to compare different images or image processing techniques. Matplotlib provides a very flexible framework for creating complex layouts of subplots.

# Display the original and filtered image side by side
fig, axes = plt.subplots(1, 2)
axes[0].imshow(image, cmap='gray')
axes[1].imshow(image_smooth, cmap='gray')

Wrapping Up

The world of image processing with Matplotlib and Python is vast and full of possibilities. From basic manipulations like image cropping and scaling to advanced techniques like image segmentation, this library offers an extensive set of tools for both data visualization and image processing.

To further your skills, consider exploring various data visualization platforms such as Snowflake, Clickhouse, and AWS. These platforms can integrate seamlessly with Python and Matplotlib, providing a comprehensive data analysis and visualization workflow.

Remember, the journey of mastering Matplotlib is a marathon, not a sprint. So, take it one plot at a time!