How can i use zero-padding in an image?

Hello ,
I have an image(512x512) and i want to do zero-padding in order to covolute it with a filter .
The problem here is that i dont know how to do that ,meaning that i dont know where the zeros should be (around the image or next to it) and furthermore the size of the zero-padding.
Any help would be valuable.

 Réponse acceptée

Image Analyst
Image Analyst le 13 Oct 2020

2 votes

There is a built-in function for that. It's called padarray().

5 commentaires

Gn Gnk
Gn Gnk le 13 Oct 2020
Ok , pad= padarray(image , ..) i dont know how many zeros should i put . The image is 512x512 and the filter is 3x3
If you want the output to have the same size as the input image, then calculate padding using
floor((n-1)/2); % n=3 for a 3x3 matrix
This padding is added on all sides of the image.
Full demo:
grayImage = imread('cameraman.tif');
whos grayImage % 256 x 256
windowSize = 3; % Filter window's full width.
% Compute the number of layers of pixels with value 0 to surround the image with.
numLayers = floor(windowSize/2) % Will be 1
grayImage2 = padarray(grayImage, [numLayers, numLayers]); % Create new image, or use img if you want to replace the image instead of creating a new one.
whos grayImage2 % Will be 258 x 258
Gn Gnk
Gn Gnk le 13 Oct 2020
Great ! Thank you a lot.
Image Analyst
Image Analyst le 13 Oct 2020
Manual convolution demo attached.

Connectez-vous pour commenter.

Plus de réponses (1)

Ameer Hamza
Ameer Hamza le 13 Oct 2020
Modifié(e) : Ameer Hamza le 13 Oct 2020
You don't need to do padding yourself. imfilter(): https://www.mathworks.com/help/images/ref/imfilter.html automatically does it based on the option you pass
filtered_image = imfilter(img, fil, 'same')
If you want to understand the concept behind it, then this link might be helpful: https://machinelearningmastery.com/padding-and-stride-for-convolutional-neural-networks/

1 commentaire

Gn Gnk
Gn Gnk le 13 Oct 2020
Thank you for your quick response . I am familiar with imfilter() but i actually want to do this process by myself , thats why i am really confused.

Connectez-vous pour commenter.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by