【发布时间】:2016-02-20 11:23:13
【问题描述】:
在一个充满zeros 的二维方形网格(矩阵)中,我需要创建一个充满ones 的子矩阵,该子矩阵的形状尽可能接近圆形。我知道在使用单元格或像素时无法精确表示圆,因此我的目标是离散圆。
我能想到的最好的东西是这段代码,它产生方形子矩阵(下图中的蓝色方块):
from __future__ import division
import numpy
import matplotlib.pyplot as plt
import matplotlib.colors as mc
import random
import os
import math
n=101 #Grid size
empty_lattice=numpy.zeros((n,n)) #The empty 2D grid
x=int(numpy.random.uniform(0,n-1)) #X coord. top left corner
y=int(numpy.random.uniform(0,n-1)) #Y coord. top left corner
side=int(numpy.random.uniform(15,n)) #Side of the square approximating the circle
max_y=n-y #Checks the distance between the y of the submatrix origin and the matrix vertical boundary
max_x=n-x #Checks the distance between the x of the submatrix origin and the matrix horizontal boundary
max_width=0 #Initializes a maximum width for the loading submatrix
if max_y<max_x: #This assigns the minimum value between max_y and max_x to max_width, so that the submatrix is always a square
max_width=max_y
else:
max_width=max_x
if side>max_width:
for i in range(0,max_width):
for j in range(0, max_width):
empty_lattice[x+i][y+j]=1
else:
for i in range(0, side):
for j in range(0, side):
empty_lattice[x+i][y+j]=1
现在,从视觉上看,这会转化为下图,但正如您所知,蓝色正方形和内切圆在面积方面存在明显差异:
我的问题:我怎样才能修改我的代码,以便能够“平滑”我的正方形的角,以便出现类似于圆形的东西?
编辑
即使圆圈不完全位于网格边界内,也应该绘制圆圈(看图片)。
【问题讨论】:
-
这可以让我产生截断的圆圈吗?当圆心在边界上或越过边界时,它们就会出现,但仍有空间绘制圆的一部分。
-
也许至少阅读他链接的文章的内容部分,这将回答您的问题。您还可以制作更大的网格,绘制完整的圆圈并在之后截断。
标签: python numpy multidimensional-array grid shapes