3

I have many images of different sizes which is like images = [np.array(shape=(100, 200)), np.array(shape=(150, 100)), np.array(shape=200, 50)...]

Is there any efficient and convenient way to pad zeros to small images (pad zeros at the right-bottom) and get a numpy array of size (3, 200, 200)?

Tauta
  • 907
  • 1
  • 8
  • 12

2 Answers2

3

To add padding to a Numpy array you can use the followings:

Center padding:

shape = (200,200)
padded_images = [np.pad(a, np.subtract(shape, a.shape), 'constant', constant_values=0) for a in images]

Right bottom padding:

def pad(a):
    """Return bottom right padding."""
    zeros = np.zeros((200,200))
    zeros[:a.shape[0], :a.shape[1]] = a
    return zeros

vectorized_pad = np.vectorize(pad)
padded_images = vectorized_pad(images)
Luca Cappelletti
  • 2,485
  • 20
  • 35
0

Based on this solution, you can do the following to pad an image on the right and bottom with zeros:

shape=(200,200)

new_images = [np.zeros(shape) for _ in range(len(images))]

for i,image in enumerate(images):
    new_images[i][:image.shape[0], :image.shape[1]] = image

Example:

For a minimal example, padding a set of small images to shape (5,5):

# Create random small images
images=[np.random.randn(2,3), np.random.randn(3,3), np.random.randn(5,5)]

# Print out the shape of each image just to demonstrate
>>> [image.shape for image in images]
[(2, 3), (3, 3), (5, 5)]
# Print out first image just to demonstrate
>>> images[0]
array([[-0.49739434,  1.06979644, -0.52647292],
       [ 1.21681931, -0.96205689,  0.050574  ]])

# Set your desired shape
shape=(5,5)

# Create array of zeros of your desired shape
new_images = [np.zeros(shape) for _ in range(len(images))]

# loop through and put in your original image values in the beginning
for i,image in enumerate(images):
    new_images[i][:image.shape[0], :image.shape[1]] = image

# print out new image shapes to demonstrate
>>> [image.shape for image in new_images]
[(5, 5), (5, 5), (5, 5)]
# print out first image of new_images to demonstrate:
>>> new_images[0]
array([[-0.49739434,  1.06979644, -0.52647292,  0.        ,  0.        ],
       [ 1.21681931, -0.96205689,  0.050574  ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
       [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])
sacuL
  • 49,704
  • 8
  • 81
  • 106