Campbell Hutcheson
Campbell Hutcheson

Reputation: 869

3D slice from 3D array

I have a large 3D, N x N x N, numpy array with a value at each index in the array.

I want to be able to take cubic slices from the array using a center point:

def take_slice(large_array, center_point):
    ...
    return cubic_slice_from_center

To illustrate, I want the cubic_slice_from_center to come back with the following shape, where slice[1][1][1] would be the value of the center point used to generate the slice:

print(cubic_slice_from_center)

array([[[0.32992015, 0.30037145, 0.04947877],
        [0.0158681 , 0.26743224, 0.49967057],
        [0.04274621, 0.0738851 , 0.60360489]],

       [[0.78985965, 0.16111745, 0.51665212],
        [0.08491344, 0.30240689, 0.23544363],
        [0.47282742, 0.5777977 , 0.92652398]],

       [[0.78797628, 0.98634545, 0.17903971],
        [0.76787071, 0.29689657, 0.08112121],
        [0.08786254, 0.06319838, 0.27050039]]])

I looked at a couple of ways to do this. One way was the following:

def get_cubic_slice(space, slice_center_x, slice_center_y, slice_center_z):
    
    return space[slice_center_x-1:slice_center_x+2,
                 slice_center_y-1:slice_center_y+2,
                 slice_center_z-1:slice_center_z+2]

This works so long as the cubic slice is not on the edge but, if it is on the edge, it returns an empty array!

Sometimes, the center point of the slice will be on the edge of the 3D numpy array. When this occurs, rather than return nothing, I would like to return the values of the slice of cubic space that are within the bounds of the space and, where the slice would be out of bounds, fill the return array with np.nan values.

For example, for a 20 x 20 x 20 space, with indices 0-19 for the x, y and z axes, I would like the get_cubic_slice function to return the following kind of result for the point (0,5,5):

print(get_cubic_slice(space,0,5,5))

array([[[np.nan, np.nan, np.nan],
            [np.nan , np.nan, np.nan],
            [np.nan, np.nan , np.nan]],
    
           [[0.78985965, 0.16111745, 0.51665212],
            [0.08491344, 0.30240689, 0.23544363],
            [0.47282742, 0.5777977 , 0.92652398]],
    
           [[0.78797628, 0.98634545, 0.17903971],
            [0.76787071, 0.29689657, 0.08112121],
            [0.08786254, 0.06319838, 0.27050039]]]) 

What would be the best way to do this with numpy?

Upvotes: 0

Views: 399

Answers (1)

Bhargav Bechara
Bhargav Bechara

Reputation: 11

x = np.arange(27).reshape(3,3,3)

[[[ 0 1 2] [ 3 4 5] [ 6 7 8]]

[[ 9 10 11] [12 13 14] [15 16 17]]

[[18 19 20] [21 22 23] [24 25 26]]]

x[1][1][2]

14

x[1:, 0:2, 1:4]

[[[ 0] [ 3]]

[[ 9] [12]]

[[18] [21]]]

This is the way how we can do slicing in 3D array

Upvotes: 1

Related Questions