Skip to content
Advertisement

How to add a row of pixels at the bottom and to the right of an image?

So Im experiencing an issue with a framework that Im working with, where the images sort of get translated by 1 pixel downwards and one pixel to the left (making the pixel data wrong).

To counteract this I would like to add a one pixel “padding” then at the bottom & to the left. The script needs to be relatively fast as its an interactive software Im working with, so iterating over the pixels in a python for loop wont work as an option 😅

I have Numpy & Pillow installed already, so those modules are very welcome to be used in any solutions

The tricky part is, the new row of pixels needs to “blend in” with the pixels next to them (so ideally the padding to the left would steal the color of its right neigbour, and the pixels at the bottom would take the color from the pixel right above) – they cant just all be black.

Advertisement

Answer

You can expand a PIL Image like this.

You can then make it into a Numpy array using:

na = np.array(PILImage)

You can then set the first column and last row using Numpy indexing:

na[:, 0]  = na[:, 1]   # first col = second col
na[-1, :] = na[-2, :]  # last row = penultimate row

Then make it back into a PIL image with:

im = Image.fromarray(na)
Advertisement