我正在处理图像,我想用零填充 numpy 数组。 我看了np.pad
对于填充单个数组,效果很好
x = np.array([[1,2],[3,4]])
y = np.pad(x,(1,1), 'constant')
x
=> array([[1, 2],
[3, 4]])
y
=> array([[0, 0, 0, 0],
[0, 1, 2, 0],
[0, 3, 4, 0],
[0, 0, 0, 0]])
如果列表/数组中有 x 类型
数组,例如
c_x=np.array([[[2,2],[2,3]],[[3,2],[2,3]],[[4,4],[2,3]]])
c_y=np.pad(c_x,((0,0),(1,1),(0,0)),'constant') #padding is present only on top and bottom
由于这样的数组包含R、G、B channel ,所以在填充时也可以考虑到这一点吗?
编辑:
假设c_x
在具有RGB channel 的28x28像素上存储10张图像的列表
现在我想填充所有10张图片,所以修改后10张图片大小为30x30,边框像素为[0,0,0]
最佳答案
我不清楚你想要的输出是什么,但我认为它是 np.pad(c_x, ((1,1), (0,0), (0,0)), mode='constant')
或 np.pad(c_x, ((0,0), (1,1), (1,1)), mode='constant')
:
In [228]: c_x
Out[228]:
array([[[2, 2],
[2, 3]],
[[3, 2],
[2, 3]],
[[4, 4],
[2, 3]]])
In [229]: np.pad(c_x, ((1,1), (0,0), (0,0)), mode='constant')
Out[229]:
array([[[0, 0],
[0, 0]],
[[2, 2],
[2, 3]],
[[3, 2],
[2, 3]],
[[4, 4],
[2, 3]],
[[0, 0],
[0, 0]]])
In [230]: np.pad(c_x, ((0,0), (1,1), (1,1)), mode='constant')
Out[230]:
array([[[0, 0, 0, 0],
[0, 2, 2, 0],
[0, 2, 3, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 3, 2, 0],
[0, 2, 3, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
[0, 4, 4, 0],
[0, 2, 3, 0],
[0, 0, 0, 0]]])
关于numpy:用零填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44145948/