numpy: padding array with zeros

Viewed 18237

I am working with images and I want to pad numpy array with zeros. I looked at np.pad

For padding single array it works fine

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]])

How to implement if we have x type arrays in a list/array , like

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

As such arrays contains R,G,B channel, Can that too be accounted when padding?

edit:

Say c_x stores list of 10 images on 28x28 pixels with RGB channel

Now I want to pad all 10 images , So after modifying 10 images are of 30x30 with pixels on border as [0,0,0]

4 Answers

try this. with use of np.pad I know I m late but, It might help someone. :)

def padwithzero(vector, pad_width, iaxis, kwargs):
    vector[:pad_width[0]] = 0
    vector[-pad_width[1]:] = 0
    return vector


tmp_mainImg = np.pad(mainImg, 1, padwithzero)

print(tmp_mainImg)

I updated @Divakar's answer for 2D matrices:

import numpy
def pad2D(c_x, padlen=1):
    m, n = c_x.shape
    c_y = np.zeros((m + 2 * padlen, n + 2 * padlen), dtype = c_x.dtype)
    c_y[padlen:-padlen, padlen:-padlen] = c_x
    return c_y

this should also work with Numba!

import numpy as np
from numba import jit
@jit(nopython = True)
def pad2D(c_x, padlen=1):
    m, n = c_x.shape
    c_y = np.zeros((m + 2 * padlen, n + 2 * padlen), dtype = c_x.dtype)
    c_y[padlen:-padlen, padlen:-padlen] = c_x
    return c_y
Related