【发布时间】:2016-02-21 17:34:59
【问题描述】:
我需要在matplotlib 中实现Midpoint Circle Algorithm,以便在200x200 单元格的方形网格上光栅化一个圆。也请参考我的other question。
感谢this answer,我能够找到一些我认为可以完美运行的代码。我唯一的问题是我不知道如何整合和修改它以确保matplotlib 绘制一个实心圆,里面有1,外面有0。
这就是我使用matplotlib 实现脚本的方式:
import numpy
import matplotlib.pyplot as plt
n=200 #Grid size, 4 times my visualized output in order to be able to truncate some circles
empty_lattice=numpy.zeros((n,n)) #The empty 2D grid
radius=int(numpy.random.uniform(30,90)) #Radius
xc=int(numpy.random.uniform(0,n-radius)) #X center
yc=int(numpy.random.uniform(0,n-radius)) #Y center
x=0
y=radius
d=3-2*radius
while (x<=y):
for hor in range(0,x): #This loop is my unfortunate attempt to fill the circle with 1s
for ver in range(0,y):
empty_lattice[xc+x][yc+y]=1 #1st octant
empty_lattice[xc-x][yc+y]=1 #2nd octant
empty_lattice[xc+x][yc-y]=1 #3rd octant
empty_lattice[xc-x][yc-y]=1 #4th octant
empty_lattice[xc+y][yc+x]=1 #5th octant
empty_lattice[xc-y][yc+x]=1 #6th octant
empty_lattice[xc+y][yc-x]=1 #7th octant
empty_lattice[xc-y][yc-x]=1 #8th octant
if (d<0):
d=d+4*x+6
else:
d=d+4*(x-y)+10
y=y-1
x=x+1
现在,这是我得到的,但你看到我的圆圈是空的,并且在它底部的水平线上有一个“间隙”。这个间隙出现在每个八分圆交叉点处。 如何修改我的代码以填补圆圈和空白?
编辑
采用the answer provided below后,发现下图中画了两个镜像圆。我认为这个错误来自我的原始脚本,而不是答案。我只想要每个图像中的一个圆圈。 我怎样才能摆脱这个功能?
【问题讨论】:
-
您可能想查看
skimage,它有一套工具可以为您处理这类事情。如果你想自己做,我强烈怀疑用广播做这个会更快(通过让 numpy 在 c 中做循环而不是在 python 中自己做)。
标签: python algorithm matplotlib geometry rasterizing