Arrays 使用meshgrid在阵列的中心创建一个球体,而不使用for循环,将创建外壳瑕疵
我想实现下面的代码,避免循环以提高速度。是否有任何方法可以这样做,以便我可以创建一个以numpy数组为中心的球体Arrays 使用meshgrid在阵列的中心创建一个球体,而不使用for循环,将创建外壳瑕疵,arrays,python-3.x,numpy,matplotlib,Arrays,Python 3.x,Numpy,Matplotlib,我想实现下面的代码,避免循环以提高速度。是否有任何方法可以这样做,以便我可以创建一个以numpy数组为中心的球体 def Create_Sphere(square_numpy_array, pixel_min, pixel_max, HU, Radius_sq ): new_array = np.empty_like(square_numpy_array) for k in range(pixel_min, pixel_max, 1): for i in range(pixel_m
def Create_Sphere(square_numpy_array, pixel_min, pixel_max, HU, Radius_sq ):
new_array = np.empty_like(square_numpy_array)
for k in range(pixel_min, pixel_max, 1):
for i in range(pixel_min, pixel_max, 1):
for j in range(pixel_min, pixel_max, 1):
r_sq = (i - 255)**2 + (j - 255)**2 + (k - 255)**2
if r_sq <= Radius_sq:
new_array[k, i, j] = HU + 1000
return new_array
def创建球体(正方形数组、像素最小值、像素最大值、HU、半径平方):
新数组=np.empty类似(正方形数组)
对于范围内的k(最小像素,最大像素,1):
对于范围内的i(像素最小值,像素最大值,1):
对于范围内的j(最小像素,最大像素,1):
r_sq=(i-255)**2+(j-255)**2+(k-255)**2
如果r_sq我意识到使用无符号int会导致减法错误。最后的工作解决方案如下
def Sphere(HU):
num_pix = int(400)
radius =100
Radius_sq_pixels = (radius)**2
sphere_pixel_HU = HU
center_pixel = int(num_pix/2-1)
new_array = np.zeros((num_pix, num_pix, num_pix))
m,n,r = new_array.shape
x = np.arange(0, m, 1)
y = np.arange(0, n, 1)
z = np.arange(0, r, 1)
xx,yy,zz = np.meshgrid(x,y,z,indexing = 'ij',sparse = True)
X = (xx - center_pixel)
Y = (yy - center_pixel)
Z = (zz - center_pixel)
mask = ((X**2) + (Y**2) + (Z**2)) < Radius_sq_pixels #create sphere mask
new_array = sphere_pixel_HU * mask #assign values
new_array = new_array.astype(np.uint16) #change datatype
plt.imshow(new_array[int(num_pix/2)])
plt.show()
return new_array
def球体(HU):
num_pix=int(400)
半径=100
半径×平方像素=(半径)**2
球体\u像素\u HU=HU
中心像素=整数(数字像素/2-1)
新数组=np.0((num_pix,num_pix,num_pix))
m、 n,r=new_array.shape
x=np.arange(0,m,1)
y=np.arange(0,n,1)
z=np.arange(0,r,1)
xx,yy,zz=np.meshgrid(x,y,z,索引='ij',稀疏=真)
X=(xx-中心像素)
Y=(yy-中心像素)
Z=(zz-中心像素)
遮罩=((X**2)+(Y**2)+(Z**2))
我意识到使用无符号整数会导致减法错误。最后的工作解决方案如下
def Sphere(HU):
num_pix = int(400)
radius =100
Radius_sq_pixels = (radius)**2
sphere_pixel_HU = HU
center_pixel = int(num_pix/2-1)
new_array = np.zeros((num_pix, num_pix, num_pix))
m,n,r = new_array.shape
x = np.arange(0, m, 1)
y = np.arange(0, n, 1)
z = np.arange(0, r, 1)
xx,yy,zz = np.meshgrid(x,y,z,indexing = 'ij',sparse = True)
X = (xx - center_pixel)
Y = (yy - center_pixel)
Z = (zz - center_pixel)
mask = ((X**2) + (Y**2) + (Z**2)) < Radius_sq_pixels #create sphere mask
new_array = sphere_pixel_HU * mask #assign values
new_array = new_array.astype(np.uint16) #change datatype
plt.imshow(new_array[int(num_pix/2)])
plt.show()
return new_array
def球体(HU):
num_pix=int(400)
半径=100
半径×平方像素=(半径)**2
球体\u像素\u HU=HU
中心像素=整数(数字像素/2-1)
新数组=np.0((num_pix,num_pix,num_pix))
m、 n,r=new_array.shape
x=np.arange(0,m,1)
y=np.arange(0,n,1)
z=np.arange(0,r,1)
xx,yy,zz=np.meshgrid(x,y,z,索引='ij',稀疏=真)
X=(xx-中心像素)
Y=(yy-中心像素)
Z=(zz-中心像素)
遮罩=((X**2)+(Y**2)+(Z**2))
这应该非常接近-这应该非常接近-