是否有与numpy.pad()
相反的功能?
我正在寻找的是一个(统一)减少每个方向上的numpy数组(矩阵)的尺寸的函数。我尝试使用负值调用numpy.pad()
,但它出错:
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')
错误:ValueError: ((-1, 1), (1, 1), (1, 1)) cannot contain negative values.
我理解这个函数numpy.pad()
不会带负值,但有numpy.unpad()
或类似的东西吗?
答案 0 :(得分:10)
正如mdurant建议的那样,只需使用切片索引:
In [59]: B[1:-1, 1:-1, 1:-1]
Out[59]:
array([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
答案 1 :(得分:4)
您想要的操作:
C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')
可以替换为pad
和常规切片:
C = np.pad(B, ((0,1),(1,1),(1,1)), mode='constant')[1:,...]
答案 2 :(得分:0)
一般的解决方法是:
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)
答案 3 :(得分:0)
这是用于居中展开的功能:
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