Ttp waala
Ttp waala

Reputation: 99

Padding an image in Python

I am trying to add columns and rows on all sides.

padded_array = np.zeros([img.shape[0] + (size//2) + (size//2), img.shape[1] + (size//2) + (size//2)])
padded_array[size//2 : padded_array.shape[0]-(size//2), size//2 : padded_array.shape[1]-(size//2)] = gray

Here, img is the original image and gray is the gray-scaled image and shape of both of them is same. Now, I am trying to create a padded_array by adding (size//2) rows on top and below and (size//2) columns left and right.

size is always odd.

When I try to pad, I don't understand why the gray image is not broadcasted into the padded array. Instead, what it is doing is broadcasting value 255 on all pixels in that range of gray image and padded rows and columns are left blank.

I am adding the screenshots of both the images, please have a look.

  1. Gray Scale Image is :

enter image description here

  1. Padded Image after broadcasting gray is :

enter image description here

Upvotes: 0

Views: 2349

Answers (2)

Ttp waala
Ttp waala

Reputation: 99

The mistake here was while defining the padded_array I didn't define the data type of array to be int, it was float by default and that was the reason for white image, as soon as I defined the data in padded_array are int, everything turned out fine.

Upvotes: 0

Ahx
Ahx

Reputation: 7985

You can divide image width / image height and multiply with a constant.

import matplotlib.pyplot as plt


def pad(image, h=2):
    w = (image.shape[0]/image.shape[1]) * h
    plt.figure(figsize=(w, h))
    plt.imshow(im)
    plt.axis('off')
    plt.show()


im = plt.imread('blur.png')
pad(im)

Output:

enter image description here

Upvotes: 1

Related Questions