如何在ndarray中创建一个球体? [英] How to create a sphere inside an ndarray?
问题描述
我有一个大小为32x32x32
的ndarray.我想在数组内部创建一个球体,其中心为(x,y)
,半径为4个像素.球形的值为1,而数组的值为0.如何在python中完成?
I have a ndarray of size 32x32x32
. I want to create a sphere inside the array with the center at (x,y)
and a radius of 4 pixels. The value of the sphere is 1 while value of the array is 0. How can this be done in python?
这是生成数组的代码:
import numpy as np
A = np.zeros((32,32,32))
print (A)
推荐答案
很好的问题.您可以尝试以下代码.在下面提到的代码中,AA
是您想要的矩阵. =)
Very good question. You can try the following code. In the below mentioned code AA
is the matrix that you want. =)
import numpy as np
from copy import deepcopy
''' size : size of original 3D numpy matrix A.
radius : radius of circle inside A which will be filled with ones.
'''
size, radius = 5, 2
''' A : numpy.ndarray of shape size*size*size. '''
A = np.zeros((size,size, size))
''' AA : copy of A (you don't want the original copy of A to be overwritten.) '''
AA = deepcopy(A)
''' (x0, y0, z0) : coordinates of center of circle inside A. '''
x0, y0, z0 = int(np.floor(A.shape[0]/2)), \
int(np.floor(A.shape[1]/2)), int(np.floor(A.shape[2]/2))
for x in range(x0-radius, x0+radius+1):
for y in range(y0-radius, y0+radius+1):
for z in range(z0-radius, z0+radius+1):
''' deb: measures how far a coordinate in A is far from the center.
deb>=0: inside the sphere.
deb<0: outside the sphere.'''
deb = radius - abs(x0-x) - abs(y0-y) - abs(z0-z)
if (deb)>=0: AA[x,y,z] = 1
以下是size=5
和radius=2
(在形状为5*5*5
的numpy数组内半径为2
像素的球体)的输出示例:
Following is an example of the output for size=5
and radius=2
(a sphere of radius 2
pixels inside a numpy array of shape 5*5*5
):
[[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 1. 0. 0.]
[0. 1. 1. 1. 0.]
[1. 1. 1. 1. 1.]
[0. 1. 1. 1. 0.]
[0. 0. 1. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 1. 1. 1. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]]
[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
我没有按照要求的尺寸和半径(size=32
和radius=4
)打印输出,因为输出会很长.
I haven't printed the output for the size and radius that you had asked for (size=32
and radius=4
), as the output will be very long.
这篇关于如何在ndarray中创建一个球体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!