web-dev-qa-db-fra.com

matplotlib: comment dessiner un rectangle sur une image

Comment dessiner un rectangle sur une image, comme ceci: 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)

Je ne sais pas quoi faire le prochain.

96
KAI ZHAO

Vous pouvez ajouter un correctif Rectangle aux axes matplotlib.

Par exemple (en utilisant l'image du tutoriel ici ):

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

enter image description here

172
tmdavison

Vous devez utiliser des correctifs.

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

Il n’ya pas besoin de sous-parcelles, et pyplot peut afficher des images PIL, ce qui peut être simplifié:

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)

Ou, la version courte:

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

De ma compréhension matplotlib est une bibliothèque de traçage.

Si vous souhaitez modifier les données d'image (par exemple, dessiner un rectangle sur une image), vous pouvez utiliser ImageDraw de PIL , OpenCV , ou quelque chose de similaire.

Voici La méthode ImageDraw de PIL pour dessiner un rectangle .

Voici l'une des méthodes OpenCV pour dessiner un rectangle .

Votre question portait sur Matplotlib, mais aurait probablement dû simplement poser des questions sur le dessin d’un rectangle sur une image.

Voici une autre question qui concerne ce que je pense que vous vouliez savoir: Dessinez un rectangle et un texte à l’aide de PIL

6
user3731622