How to pad an image in numpy?

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?

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

AI Pool Discussion: https://ai-pool.com/d/padding-images-with-numpy

原文地址:https://www.cnblogs.com/hazarapet/p/10829048.html