Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 543
Melody Williams Avatar asked Jun 07 '26 09:06

Melody Williams


2 Answers

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) 
like image 61
xdze2 Avatar answered Jun 08 '26 23:06

xdze2


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)
like image 30
Luca Anzalone Avatar answered Jun 08 '26 23:06

Luca Anzalone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!