matplotlib: how to draw a rectangle on image

前端 未结 4 1743
名媛妹妹
名媛妹妹 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:32

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

    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle
    from PIL import Image
    
    im = Image.open('stinkbug.png')
    
    # Display the image
    plt.imshow(im)
    
    # Get the current reference
    ax = plt.gca()
    
    # Create a Rectangle patch
    rect = Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')
    
    # Add the patch to the Axes
    ax.add_patch(rect)
    

    Or, the short version:

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

提交回复
热议问题