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)
我不知道下一步该做什么。
答案 0 :(得分:150)
您可以在matplotlib轴上添加Rectangle
补丁。
例如(使用教程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()
答案 1 :(得分:8)
您需要使用补丁。
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')
答案 2 :(得分:5)
据我所知matplotlib是一个绘图库。
如果要更改图像数据(例如,在图像上绘制矩形),可以使用PIL's ImageDraw,OpenCV或类似名称。
这里是PIL's ImageDraw method to draw a rectangle。
这里是OpenCV's methods for drawing a rectangle之一。
您的问题问到有关Matplotlib的问题,但可能应该问过有关在图像上绘制矩形的问题。
这是另一个问题,解决了我认为您想知道的内容: Draw a rectangle and a text in it using PIL
答案 3 :(得分:5)
不需要子图,并且pyplot可以显示PIL图像,因此可以进一步简化:
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)
或者,简称:
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'))