matplotlib: how to draw a rectangle on image matplotlib: how to draw a rectangle on image python python

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 pltimport matplotlib.patches as patchesfrom PIL import Imageim = Image.open('stinkbug.png')# Create figure and axesfig, ax = plt.subplots()# Display the imageax.imshow(im)# Create a Rectangle patchrect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')# Add the patch to the Axesax.add_patch(rect)plt.show()

enter image description here


There is no need for subplots, and pyplot can display PIL images, so this can be simplified further:

import matplotlib.pyplot as pltfrom matplotlib.patches import Rectanglefrom PIL import Imageim = Image.open('stinkbug.png')# Display the imageplt.imshow(im)# Get the current referenceax = plt.gca()# Create a Rectangle patchrect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')# Add the patch to the Axesax.add_patch(rect)

Or, the short version:

import matplotlib.pyplot as pltfrom matplotlib.patches import Rectanglefrom PIL import Image# Display the imageplt.imshow(Image.open('stinkbug.png'))# Add the patch to the Axesplt.gca().add_patch(Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none'))


You need use patches.

import matplotlib.pyplot as pltimport matplotlib.patches as patchesfig2 = plt.figure()ax2 = fig2.add_subplot(111, aspect='equal')ax2.add_patch(     patches.Rectangle(        (0.1, 0.1),        0.5,        0.5,        fill=False      # remove background     ) ) fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')