使用Matplotlib和NumPy在图像上绘制圆形。

24
我有保存圆心的NumPy数组。
import matplotlib.pylab as plt
import numpy as np
npX = np.asarray(X)
npY = np.asarray(Y)
plt.imshow(img)
// TO-DO
plt.show()

我该如何在我的图片上显示给定位置的圆?


没错。对那个问题的回答展示了如何绘制圆形,这正是你所要求的 :) - MB-F
1
如果您想直接在numpy数组上绘制圆形,可以使用Python Imaging Library。请参见我的答案https://dev59.com/CGjWa4cB1Zd3GeqPv_o3; 将draw.polygon(...)更改为draw.ellipse(...)。有关详细信息,请参阅PIL文档:http://effbot.org/imagingbook/imagedraw.htm。 - Warren Weckesser
2个回答

40

你可以使用 matplotlib.patches.Circle 图形补丁来完成此操作。

对于你的示例,我们需要循环遍历 X 和 Y 数组,然后为每个坐标创建一个圆形补丁。

以下是一个在图像上放置圆形的示例(来源于 matplotlib.cbook):

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

# Get an example image
import matplotlib.cbook as cbook
image_file = cbook.get_sample_data('grace_hopper.png')
img = plt.imread(image_file)

# Make some example data
x = np.random.rand(5)*img.shape[1]
y = np.random.rand(5)*img.shape[0]

# Create a figure. Equal aspect so circles look circular
fig,ax = plt.subplots(1)
ax.set_aspect('equal')

# Show the image
ax.imshow(img)

# Now, loop through coord arrays, and create a circle at each x,y pair
for xx,yy in zip(x,y):
    circ = Circle((xx,yy),50)
    ax.add_patch(circ)

# Show the image
plt.show()

在此输入图片描述


2
这是关于编程的相关内容。将其翻译成中文:它是在图表上画圆而不是在图像上。图像不会改变。 - Andrew Matiuk
@Andrew 可以使用 plt.savefig('grace_hopper.png') 来保存图像。 - user1953366
@user1953366 把数据保存到磁盘上永远不是一个好主意,有很多缺点——如果你想保存成百万次,它会变得非常缓慢并且会占用磁盘空间。另外,您假设图像编码是无损的。 - Andrew Matiuk
请查看我的另一个答案(这里的格式不正确) - user1953366

1
为了得到图像,不要使用plt.show,而是使用以下代码(不保存到磁盘也可以获取):
io_buf = io.BytesIO()
fig.savefig(io_buf, format='raw')#dpi=36)#DPI)
io_buf.seek(0)
img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                         newshape=(int(fig.bbox.bounds[3]), int(fig.bbox.bounds[2]), -1))
io_buf.close()
plt.close()  #To not display the image

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接