Data Visualization

Overlaying Rectangles on Images with Matplotlib

Spread the love

Matplotlib is a versatile Python library renowned for its data visualization capabilities. Beyond plotting data, it excels at image manipulation, allowing you to overlay shapes directly onto images. This tutorial demonstrates how to efficiently add rectangles to images using Matplotlib.

Table of Contents

Drawing Rectangles in Matplotlib

Before working with images, let’s master drawing rectangles on standard Matplotlib figures. This foundational step is crucial for understanding the image overlay process.

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# Create figure and axes
fig, ax = plt.subplots()

# Define rectangle
rect = patches.Rectangle((0.1, 0.1), 0.5, 0.5, linewidth=1, edgecolor='r', facecolor='none')

# Add rectangle to axes
ax.add_patch(rect)

# Set axis limits (optional)
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])

# Display plot
plt.show()

This code generates a simple rectangle. Let’s dissect it:

  • matplotlib.pyplot as plt: Imports the Matplotlib plotting library.
  • matplotlib.patches as patches: Imports the patches module, containing shape objects like rectangles.
  • patches.Rectangle((x, y), width, height): Creates a rectangle. (x, y) specifies the bottom-left corner; width and height define its dimensions. Coordinates are normalized (0 to 1).
  • linewidth, edgecolor, facecolor: Control the rectangle’s appearance. facecolor='none' creates an outline only.
  • ax.add_patch(rect): Adds the rectangle to the axes.
  • ax.set_xlim() and ax.set_ylim(): Set x and y axis limits (optional, for better visualization).

Overlaying Rectangles on Images

Now, let’s extend this to overlay rectangles onto images. We’ll use imread from Matplotlib to load the image.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.image as mpimg

# Load image
img = mpimg.imread('your_image.jpg')  # Replace with your image path

# Create figure and axes
fig, ax = plt.subplots()

# Display image
ax.imshow(img)

# Create rectangle (pixel coordinates)
rect = patches.Rectangle((100, 100), 150, 100, linewidth=2, edgecolor='b', facecolor='none')

# Add rectangle to axes
ax.add_patch(rect)

# Display plot
plt.show()

This is similar to the previous example, but:

  • mpimg.imread('your_image.jpg'): Loads the image. Remember to replace 'your_image.jpg' with your image’s path.
  • ax.imshow(img): Displays the image on the axes.
  • Rectangle coordinates (100, 100) are now in pixel coordinates. Adjust these values to position the rectangle.

This method allows you to annotate images effectively. Experiment with coordinates, sizes, colors, and line widths to customize the rectangle’s appearance and placement. Remember that coordinates are relative to the image’s pixel dimensions.

Leave a Reply

Your email address will not be published. Required fields are marked *