Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Zero Pad RGB Image?

I want to Pad an RGB Image of size 500x500x3 to 512x512x3. I understand that I need to add 6 pixels on each border but I cannot figure out how. I have read numpy.pad function docs but couldn't understand how to use it. Code snippets would be appreciated.

like image 833
Syed Nauyan Rashid Avatar asked Sep 05 '25 03:09

Syed Nauyan Rashid


2 Answers

If you need to pad 0:

RGB = np.pad(RGB, pad_width=[(6, 6),(6, 6),(0, 0)], mode='constant')

Use constant_values argument to pad different values (default is 0):

RGB = np.pad(RGB, pad_width=[(6, 6),(6, 6),(0, 0)], mode='constant', constant_values=0, constant_values=[(3,3),(5,5),(0,0)]))
like image 174
Ehsan Avatar answered Sep 07 '25 20:09

Ehsan


We can try to get a solution by adding border padding, but it would get a bit complex. I would like to suggest you can alternate approach. First we can create a canvas of size 512x512 and then we place your original image inside this canvas. You can get help from the following code:

import numpy as np

# Create a larger black colored canvas
canvas = np.zeros(512, 512, 3)

canvas[6:506, 6:506] = your_500_500_img

Obviously you can convert 6 and 506 to a more generalized variable and use it as padding, 512-padding, etc. but this code illustrates the concept.

like image 43
ZdaR Avatar answered Sep 07 '25 21:09

ZdaR