MATPLOTLIB: Hoe een rechthoek op de afbeelding te tekenen

Hoe een rechthoek op een afbeelding te tekenen, zoals dit:

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)

Ik weet niet hoe ik verder moet gaan.


1, Autoriteit 100%

U kunt een Rectanglepatch naar de matplotlib-assen.

Bijvoorbeeld (met behulp van de afbeelding van de tutorial hier ):

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()


2, Autoriteit 12%

Er is geen behoefte aan subplots en pyplot kan pill-afbeeldingen weergeven, dus dit kan verder worden vereenvoudigd:

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)

of, de korte versie:

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'))

3, Autoriteit 7%

U hebt patches gebruikt.

import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = 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')

Other episodes