我有一个计算3-D体积平均深度的函数。有没有一种方法可以使代码的执行时间更高效。体积具有以下形状。
volume = np.zeros((100, 240, 180))
该体积可以包含不同体素上的数字1,目的是使用体积中所有占用单元格的加权平均值来找到平均深度(平均Z坐标)。
def calc_mean_depth(volume):
'''
Calculate the mean depth of the volume. Only voxels which contain a value are considered for the mean depth
Parameters:
-----------
volume: (100x240x180) numpy array
Input 3-D volume which may contain value of 1 in its voxels
Return:
-------
mean_depth :<float>
mean depth calculated
'''
depth_weight = 0
tot = 0
for z in range(volume.shape[0]):
vol_slice = volume[z, :, :] # take one x-y plane
weight = vol_slice[vol_slice>0].size # get number of values greater than zero
tot += weight # This counter is used to serve as the denominator
depth_weight += weight * z # the depth plane into number of cells in it greater than 0.
if tot==0:
return 0
else:
mean_depth = depth_weight/tot
return mean_depth
答案 0 :(得分:0)
这应该有效。使用count_nonzero
进行求和并在最后进行平均。
def calc_mean_depth(volume):
w = np.count_nonzero(volume, axis = (1,2))
if w.sum() == 0:
return 0
else
return (np.arange(w.size) * w).sum() / w.sum()