Search code examples
pythonarraysnumpypad

Numpy padding 4D units with all zeros


I have a 4D numpy array, but each element is a variable size 3D volume. Essentially it is a numpy list of 3D volumes. So the numpy array has the shape...

(Pdb) batch_x.shape
(3,)

And take element i in that list, and it looks like this...

(Pdb) batch_x[i].shape
(7, 70, 66)

I'm trying to pad each 3D volume with zeros, with the following code...

for i in range(batch_size):
    pdb.set_trace()
    batch_x[i] = np.lib.pad(batch_x[i], (n_input_z - int(batch_x[i][:,0,0].shape[0]),
                                                    n_input_x - int(batch_x[i][0,:,0].shape[0]),
                                                    n_input_y - int(batch_x[i][0,0,:].shape[0])),
                                    'constant', constant_values=(0,0,0))
    batch_y[i] = np.lib.pad(batch_y[i], (n_input_z - int(batch_y[i][:,0,0].shape[0]),
                                                    n_input_x - int(batch_y[i][0,:,0].shape[0]),
                                                    n_input_y - int(batch_y[i][0,0,:].shape[0])),
                                    'constant', constant_values=(0,0,0))

There error is as follow...

*** ValueError: Unable to create correctly shaped tuple from (3, 5, 9)

I'm trying to pad each 3D volume such that they all have the same shape -- [10,75,75]. Keep in mind, like I showed above, batch_x[i].shape = (7,70,66) So the error message is at least showing me that my dimensions should be correct.

For evidence, debugging...

(Pdb) int(batch_x[i][:,0,0].shape[0])
7
(Pdb) n_input_z
10
(Pdb) (n_input_z - int(batch_x[i][:,0,0].shape[0]))
3

Solution

  • So stripped of the extraneous stuff, the problem is:

    In [7]: x=np.ones((7,70,66),int)
    In [8]: np.pad(x,(3,5,9),mode='constant',constant_values=(0,0,0))
    ...
    ValueError: Unable to create correctly shaped tuple from (3, 5, 9)
    

    Looks like a problem with defining the inputs to pad. I haven't used it much, but I recall it required pad size for both the start and end of each dimension.

    From its docs:

    pad_width : {sequence, array_like, int}
        Number of values padded to the edges of each axis.
        ((before_1, after_1), ... (before_N, after_N)) unique pad widths
        for each axis.
    

    So lets try a tuple of tuples:

    In [13]: np.pad(x,((0,3),(0,5),(0,9)), mode='constant', constant_values=0).shape
    Out[13]: (10, 75, 75)
    

    Can you take it from there?