Is there an efficient way to pad a matrix with zeros on all sides?

11,425

Solution 1

If you have access to the Image Processing Toolbox, you can use the function PADARRAY:

imgPadded = padarray(img, [p p], 0, 'both');

Otherwise you can simply use matrix indexing:

sz = size(img);
imgPadded = zeros([sz(1:2)+2*p size(img,3)], class(img));
imgPadded((1:sz(1))+p, (1:sz(2))+p, :) = img;

This should work for both grayscale and RGB images.

Solution 2

>> y = [zeros(P,N+2*P) ; [zeros(M,P), x, zeros(M,P)] ; zeros(P,N+2*P)];

where x is the original image matrix and y is the output should work. If the matrix has 3 planes, adjust to:

>> y = [zeros(P,N+2*P,3) ; [zeros(M,P,3), x, zeros(M,P,3)] ; zeros(P,N+2*P,3)];

Solution 3

Use padarray:

y = padarray(x, [P P]);
Share:
11,425
bjornsen
Author by

bjornsen

Updated on June 05, 2022

Comments

  • bjornsen
    bjornsen almost 2 years

    I'm performing texture synthesis on images using the Efros and Leung Algorithm. My goal is to grow the size of my current textured image and, to do it, I'd like to pad the current image matrix with zeros on all sides.

    My current plan given an original image matrix of size MxN and a desired growth size of P:
    (1) Create a target matrix of size (M+2P)x(N+2P)
    (2) Set the value of target(i+P,j+P) = original(i,j)
    (3) Run Efros and Leung

    Is there a way I can eliminate (1) and (2) and just operate on the original image to pad it in all directions with P zeros?