Is there an opposite / inverse function to numpy.pad ()?

Is there a function opposite to what it does numpy.pad()?

What I'm looking for is a function to (evenly) reduce the size of a numpy array (matrix) in each direction. I tried calling numpy.pad()with negative values, but it gave an error:

import numpy as np

A_flat = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
A = np.reshape(A_flat, (3,2,-1))

#this WORKS:
B = np.pad(A, ((1,1),(1,1),(1,1)), mode='constant')

# this DOES NOT WORK:
C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')

Error: ValueError: ((-1, 1), (1, 1), (1, 1)) cannot contain negative values.

I understand that this function numpy.pad()does not take negative values, but is there numpy.unpad()or something similar?

+4
source share
2 answers

The operation you want:

C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')

can be replaced by a combination padand a general cut:

C = np.pad(B, ((0,1),(1,1),(1,1)), mode='constant')[1:,...]
+3
source

As mdurant suggests, just use slice indexing:

In [59]: B[1:-1, 1:-1, 1:-1]
Out[59]: 
array([[[ 0,  1],
        [ 2,  3]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 8,  9],
        [10, 11]]])
+8

All Articles