📜  pyplot rectangle over image - Python (1)

📅  最后修改于: 2023-12-03 15:18:46.283000             🧑  作者: Mango

Pyplot Rectangle Over Image - Python

In Python using matplotlib, we can plot images and draw shapes like rectangles over them. This can be useful in object detection and annotation tasks.

Here is an example code snippet demonstrating how to draw a rectangle over an image using pyplot:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

# Load image
img = plt.imread('image.jpg')

# Draw rectangle
fig, ax = plt.subplots()
ax.imshow(img)
rect = patches.Rectangle((50, 50), 200, 300, linewidth=2, edgecolor='r', facecolor='none')
ax.add_patch(rect)
plt.show()

In this example, we first load the image using plt.imread and then we create a Rectangle object using the patches module. The Rectangle object takes four arguments: (x,y) coordinates of the upper left corner of the rectangle, width, and height.

We then create a Figure and Axes object using plt.subplots and display the image using ax.imshow. Finally, we add the Rectangle object to the Axes using ax.add_patch and display the plot using plt.show.

The output of the above code snippet looks like this:

Image with rectangle drawn on top of it

As you can see, a red rectangle has been drawn on top of the original image.

This technique can also be used to draw other shapes like circles, ellipses, and polygons over images. By changing the facecolor parameter to a non-empty string, we can also fill the shape with a color.

In conclusion, using pyplot and patches, we can easily draw shapes like rectangles over images in Python.