【问题标题】:Drawing circles on image with Matplotlib and NumPy使用 Matplotlib 和 NumPy 在图像上绘制圆圈
【发布时间】:2016-04-26 10:37:21
【问题描述】:

我有保存圆心的 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()

如何在图像的给定位置显示圆圈?

【问题讨论】:

标签: python numpy matplotlib plot imshow


【解决方案1】:

您可以使用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()

【讨论】:

  • 它是情节中的圆圈,而不是图像上。 img 不会改变
  • @Andrew 可以使用 plt.savefig('grace_hopper.png') 保存图像
  • @user1953366 保存到光盘从来都不是一个好主意,有很多缺点 - 如果你想制作数百万次,它会非常慢并且会导致光盘空间不足。此外,您假设图像编码是无损的。
  • 请看我的其他答案(此处格式不正确)
【解决方案2】:

要获取图像,而不是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多