Discussions>Padding images with numpy>

Padding images with numpy

Guys I need 2d padding for 3 channel images with numpy. I know that there is np.pad function, but it pads channels as well and as a result I have modified channels count, but I just need to pad only the image. How to do it?

3 votesJW330.00
1 Answers
def pad(img, h, w):
    #  in case when you have odd number
    top_pad = np.floor((h - img.shape[0]) / 2).astype(np.uint16)
    bottom_pad = np.ceil((h - img.shape[0]) / 2).astype(np.uint16)
    right_pad = np.ceil((w - img.shape[1]) / 2).astype(np.uint16)
    left_pad = np.floor((w - img.shape[1]) / 2).astype(np.uint16)
    return np.copy(np.pad(img, ((top_pad, bottom_pad), (left_pad, right_pad), (0, 0)), mode='constant', constant_values=0))

Make sure you copy the padded image, to avoid memory allocation issue.

Couldn't find what you were looking for?and we will find an expert to answer.
How helpful was this page?