0

I have a function which calculates the mean depth of a 3-D volume. Is there a way to make the code more efficient in terms of execution time. The volume is of the following shape.

volume = np.zeros((100, 240, 180))

The volume can contain the number 1 at different voxels and the objective is to find the mean depth (mean Z co-ord) using weighted average of all occupied cells in the volume.

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

1 Answer 1

0

This should work. Use count_nonzero to do the summing and do the averaging at the end.

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm...Seems to be working slower than the snippet i've posted.
I can't imagine how. Does the original snippet have a numba decorator you left off?
No I've posted exactly what I am using. I am using the %timeit function in a jupyter notebook to measure the execution time. The snippet I've posted runs in approx 7ms while your's runs in 11ms. I haven't left off any decorators

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.