Search code examples
pythonnumpypaddingpad

How to pad a RGB image with RGB values using numpy.pad


I'm trying to pad a RGB image with magenta (255, 0, 255) color with np.pad. But I'm getting an error when using RGB values as constant_values. For example:

import numpy as np
from scipy.misc import face
import matplotlib.pyplot as plt


def pad_img(img, pad_with):
    pad_value = max(img.shape[:-1])
    img_padded = np.pad(img,
                        ((0, (pad_value - img.shape[0])),  # pad bottom
                         (0, (pad_value - img.shape[1])),  # pad right
                         (0, 0)),  # don't pad channels
                        mode='constant',
                        constant_values=pad_with)

    fig, (ax1, ax2) = plt.subplots(1, 2)
    ax1.imshow(img)
    ax2.imshow(img_padded)
    plt.show()

This works fine (padding with white color):

img = face()
pad_img(img, pad_with=255)

out1

And this not (padding with magenta):

img = face()
pad_img(img, pad_with=(255, 0, 255))

Throwing:

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (3,) and requested shape (3,2)


Solution

  • I think what you are looking for is:

    img = face()
    pad_img(img, pad_with=(((255, 0, 255), (255, 0, 255)), ((255, 0, 255), (255, 0, 255)), (0, 0)))
    

    According to numpy doc constant_values is of form:

    ((before_1, after_1), ... (before_N, after_N))

    And I think that is why the error says it gets shape (3,) ((255, 0, 255)) for pad_width while it requests shape (3,2) ((((255, 0, 255), (255, 0, 255)), ((255, 0, 255), (255, 0, 255)), (0, 0)))