Is there an opposite / inverse to numpy.pad() function?
Operation you want:
C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')
can be replaced with combination of pad
and general slice:
C = np.pad(B, ((0,1),(1,1),(1,1)), mode='constant')[1:,...]
As mdurant suggests, simply 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]]])
Here is a function for centered unpadding:
def unpad(dens, pad):
"""
Input: dens -- np.ndarray(shape=(nx,ny,nz))
pad -- np.array(px,py,pz)
Output: pdens -- np.ndarray(shape=(nx-px,ny-py,nz-pz))
"""
nx, ny, nz = dens.shape
pl = pad // 2
pr = pad - pl
pdens = dens[pl[0]:nx-pr[0],
pl[1]:ny-pr[1],
pl[2]:nz-pr[2]]
return pdens
A general solution is this:
def unpad(x, pad_width):
slices = []
for c in pad_width:
e = None if c[1] == 0 else -c[1]
slices.append(slice(c[0], e))
return x[tuple(slices)]
# Test
import numpy as np
pad_width = ((0, 0), (1, 0), (3, 4))
a = np.random.rand(10, 10, 10)
b = np.pad(a, pad_width, mode='constant')
c = unpad(b, pad_width)
np.testing.assert_allclose(a, c)