【问题标题】:Python replace zeros in matrix with 'circle' of onesPython用“圆圈”替换矩阵中的零
【发布时间】:2014-05-15 09:29:04
【问题描述】:

我可以创建一个大的零矩阵并将矩阵内的矩形区域替换为如下所示:

import numpy as np

z = np.zeros((400,400))
z[192:206,196:202] = 1

如何将矩阵中的 圆形 区域替换为圆形区域?圆的半径可以任意大。

【问题讨论】:

  • 圆心一定要在正方形的中心吗?
  • @mjandrews 是的 - 有点像我的示例中的“矩形”。
  • 我在下面输入答案时发表了上述评论。您只需将中心坐标设置为 ci,cj=200,200。

标签: python numpy


【解决方案1】:

这是一种执行您所要求的方法,指定圆心和半径:

import numpy as np
import matplotlib.pyplot as plt
z = np.zeros((400,400))

# specify circle parameters: centre ij and radius
ci,cj=232,145
cr=20

# Create index arrays to z
I,J=np.meshgrid(np.arange(z.shape[0]),np.arange(z.shape[1]))

# calculate distance of all points to centre
dist=np.sqrt((I-ci)**2+(J-cj)**2)

# Assign value of 1 to those points where dist<cr:
z[np.where(dist<cr)]=1

# show result in a simple plot
fig=plt.figure()
ax=fig.add_subplot(111)
ax.pcolormesh(z)
ax.set_aspect('equal')
plt.show()

我用ax.set_aspect('equal') 表明它确实是一个圆形区域。我将其他方面,例如检查圆圈是否完全落在域的范围内,由您决定。

【讨论】:

  • 当将此解决方案与轴尺寸不等的数组一起使用时,第 9 行应为 I,J=np.meshgrid(np.arange(z.shape[1]),np.arange(z.shape[ 0]))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 2013-07-29
  • 1970-01-01
  • 2021-08-27
  • 2014-11-29
  • 2017-06-07
  • 1970-01-01
相关资源
最近更新 更多