numpy:用零填充数组

标签 numpy image-processing

我正在处理图像,我想用零填充 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/

相关文章:

java - 双线性插值异常

image - 如何裁剪/缩放用户图像,以便可以显示固定大小的缩略图而不倾斜和拉伸(stretch)?

java - 定义轮廓是否闭合

opencv - 锐化边缘

android - 检测眼球

python - Python 3 确保数组参数尺寸正确的方法是什么?

python - 查找一个数据集中的数据在另一数据集中的对应关系

python - 强制数组中非零元素之间的最小间距

python-3.x - Pyinstaller .exe 找不到 _tiffile 模块 - 加载一些压缩图像会很慢

python - 在 numpy 中执行多种方式