2016-05-25 109 views
28

矩形如何繪製一個矩形一個圖像上,像這樣: enter image description herematplotlib:如何繪製圖像

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) 

我不知道該怎麼做了下。

回答

53

您可以將Rectangle補丁添加到matplotlib軸。

例如(使用圖像從教程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() 

enter image description here

+0

謝謝您的回答!它可以工作,但看起來矩形繪製在軸上,而不是圖片本身。如果我嘗試將圖像保存到文件中,矩形將不會被保存。有沒有辦法讓矩形代替圖像上的像素值?再次感謝! –

+0

沒關係。我發現這個[鏈接](http://docs.opencv.org/3.1.0/dc/da5/tutorial_py_drawing_functions.html),它似乎工作:) –

+0

如果你仍然得到填充矩形,通過'填充= False'國旗到'Rectangle' –

4

您需要使用補丁。

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

更多的例子,你可能會發現這裏:http://matthiaseisen.com/pp/patterns/p0203/