【问题标题】:Efficient implementation of the following code snippet以下代码片段的高效实现
【发布时间】:2018-10-12 05:34:31
【问题描述】:

我有一个函数可以计算 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

【问题讨论】:

    标签: python-3.x numpy computer-vision


    【解决方案1】:

    这应该可行。最后用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()
    

    【讨论】:

    • 嗯...似乎比我发布的 sn-p 工作得慢。
    • 我无法想象如何。原来的 sn-p 有没有你留下的 numba 装饰器?
    • 不,我已经准确地发布了我正在使用的内容。我在 jupyter notebook 中使用 %timeit 函数来测量执行时间。我发布的 sn-p 运行时间约为 7 毫秒,而您的运行时间为 11 毫秒。我没有留下任何装饰器
    猜你喜欢
    • 2021-11-06
    • 2023-01-13
    • 2020-01-02
    • 2022-11-10
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多