pythonimagematplotlib

How to draw a rectangle on image


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(Image.open('dog.png'), dtype=np.uint8)
plt.imshow(im)

To make it clear, I meant to draw a rectangle on top of the image for visualization, not to change the image data.

So using matplotlib.patches.Patch would be the best option.


Solution

  • 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 = Image.open('stinkbug.png')
    
    # Create figure and axes
    fig, ax = plt.subplots()
    
    # Display the image
    ax.imshow(im)
    
    # Create a Rectangle patch
    rect = patches.Rectangle((50, 100), 40, 30, linewidth=1, edgecolor='r', facecolor='none')
    
    # Add the patch to the Axes
    ax.add_patch(rect)
    
    plt.show()
    

    enter image description here