gpt4 book ai didi

python - 根据圆的面积更改 numpy 数组中的值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:48 24 4
gpt4 key购买 nike

上下文

我需要在 python 中测量组合圆的面积。我想出了使用 numpy 数组的方法。首先,我用零填充一个网格(numpy 数组),网格中的每个位置对应 0.5cm 的长度。然后,我将圆心放到网格上,并在网格中将此值更改为 1。我知道圆的半径,所以我可以计算圆的面积,因为我知道圆的面积,我将网格中的零点更改为落在圆面积内的零点。然后我计算网格中的频率并用它来计算组合圆的面积,因为我知道网格中每个位置的长度我可以计算面积。目前这是一种非常粗粒度的方法,我计划在确定算法后将其更改为更细的粒度。

示例

如果您查看我在下面发布的图片,它可以更好地描述我的想法。我的网格上有两个圆圈(红线),圆圈的中心标有蓝色方 block ,圆圈占据的区域为浅橙色。我想将标有橙色的区域更改为那些。我目前可以将橙色方 block 水平和垂直更改为圆心,但中心的对角线框给我带来了麻烦。

enter image description here

当前代码

class area():

def make_grid(self):
'''
Each square in the grid represents 0.5 cm
'''
import numpy as np
grid = np.zeros((10,10))
square_length = 0.5
circles = {'c1':[[4,2],1.5],'c2':[[5,6],2.0]}

print grid
for key,val in circles.iteritems():
grid[val[0][0]][val[0][1]] = 1
area = int((val[1] - square_length)/0.5)
for i in xrange(1,area+1):
grid[val[0][0]][val[0][1]+i] = 1 # Change column vals in +ve direction
grid[val[0][0]][val[0][1]-i] = 1 # Chnage column vals in -ve direction
grid[val[0][0]+i][val[0][1]] = 1 # Chnage row vals in +ve direction
grid[val[0][0]-i][val[0][1]] = 1 # Chnage row vals in -ve direction

print ''
print grid

在上面的字典中,键是圆的名称,值中的第一个元素是圆心坐标,第二个元素是圆的半径。

代码输出:

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 1. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 1. 0. 0. 0. 1. 0. 0. 0.]
[ 1. 1. 1. 1. 1. 0. 1. 0. 0. 0.]
[ 0. 0. 1. 1. 1. 1. 1. 1. 1. 1.]
[ 0. 0. 1. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

最佳答案

根据@Jaime 的评论更新。

我可能会从这样的事情开始。重点是圆内像素的正确计算。

import numpy as np
import matplotlib.pyplot as plt

grid = np.zeros((10,10), dtype=np.bool)
square_length = 0.5
circles = {'c1':[[4,2],1.5],'c2':[[5,6],2.0]}

# Generate arrays of indices/coordiates so we can do the
# calculations the Numpy way, without resorting to loops
# I always get the index order wrong so double check...
xx = np.arange(grid.shape[0])
yy = np.arange(grid.shape[1])

for val in circles.itervalues():
radius = val[1]
# same index caveat here
# Calling Mr Pythagoras: Find the pixels that lie inside this circle
inside = (xx[:,None] - val[0][0]) ** 2 + (yy[None, :] - val[0][1]) ** 2 <= (radius ** 2)
# do grid & inside and initialize grid with ones for intersection instead of union
grid = grid | inside

plt.imshow(grid)
plt.show()

如果您在十字路口之后,请注意您的圆心相距 sqrt(17) ~= 4.123.. 个单位,两个半径之和为 3.5 所以实际上没有重叠。

关于python - 根据圆的面积更改 numpy 数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15432294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com