matplotlib: how to draw a rectangle on image

前端 未结 4 1733
名媛妹妹
名媛妹妹 2020-11-28 02:01

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

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
im = np.array(Image.open(\'dog.png\'         


        
4条回答
  •  情歌与酒
    2020-11-28 02:24

    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
    import numpy as np
    
    im = np.array(Image.open('stinkbug.png'), dtype=np.uint8)
    
    # Create figure and axes
    fig,ax = plt.subplots(1)
    
    # 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()
    

提交回复
热议问题