Melody Williams
Melody Williams

Reputation: 31

How to pad an image using np.pad in python?

I'm currently processing images that consist of a stack, 18 images per stack. I then deconvolve these images to produce cleaner sharper images. However when doing this I get border artifacts. I have spent some time writing code so as to determine how wide a pad I would need to pad these images, however I am unsure of how to use np.pad so that I may produce padded images. This is my code so far:

xextra = pad_width_x / 2
yextra = pad_width_y / 2
print (xextra)
print (yextra)

Where xextra and yextra are the pad widths I will be using. I understand that I will need to use this line of code to pad the array:

no_borders = np.pad(sparsebeadmix_sheet_cubic_deconvolution, pad_width_x, mode='constant', constant_values=0)

However how will I be able to process my stack of images (18 images) through this and save them as outputs?

I hope this makes sense!

Upvotes: 3

Views: 14474

Answers (2)

Luca Anzalone
Luca Anzalone

Reputation: 749

In case someone is wondering how to pad a batch of images instead:

def pad_images(images: np.ndarray, top=0, bottom=0, left=0, right=0, constant=0.0) -> np.ndarray:
    assert len(images.shape) == 4, 'not a batch of images!'
    return np.pad(images, ((0, 0), (top, bottom), (left, right), (0, 0)),
                  mode='constant', constant_values=constant)

Example usage:

# assuming `image_batch` has shape (B, H, W, C)
pad_images(image_batch, top=1, bottom=1, constant=0.5)

Upvotes: 1

xdze2
xdze2

Reputation: 4151

If your stack is a nxny18 array:

import numpy as np

image_stack = np.ones((2, 2, 18))

extra_left, extra_right = 1, 2
extra_top, extra_bottom = 3, 1

np.pad(image_stack, ((extra_top, extra_bottom), (extra_left, extra_right), (0, 0)),
       mode='constant', constant_values=3) 

Upvotes: 8

Related Questions