Fix Python – matplotlib: how to draw a rectangle on image


Asked By – Kai ZHAO

How to draw a rectangle on an image, like this:
enter image description here

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
im = np.array('dog.png'), dtype=np.uint8)

I don’t know how to proceed.

Now we will see solution for issue: matplotlib: how to draw a rectangle on image


You can add a Rectangle patch to the matplotlib Axes.

For example (using the image from the tutorial here):

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image

im ='stinkbug.png')

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

# Display the image

# Create a Rectangle patch
rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')

# Add the patch to the Axes

enter image description here

This question is answered By – tmdavison

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0