bjornsen
bjornsen

Reputation: 604

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

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?

Upvotes: 3

Views: 11907

Answers (3)

Amro
Amro

Reputation: 124563

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.

Upvotes: 4

Simon
Simon

Reputation: 32883

Use padarray:

y = padarray(x, [P P]);

Upvotes: 3

mtrw
mtrw

Reputation: 35088

>> 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)];

Upvotes: 3

Related Questions