Reputation: 1326
I'm trying to pad a matrix filled with zeros at the borders with the values at the pixel which is closest to the border, for example:
A = rand(5);
Z = zeros(9);
Z(3:7, 3:7) = A;
Now I'd like to complete the matrix borders in the following way:
I'm looking for a nice solution without any for-loops
EDIT:
It should look like this:
Upvotes: 0
Views: 1385
Reputation: 12737
% Create a random image
I = round(rand(8)*70);
% Number of pixels to pad on each side
padSize = 3;
% Create a resulting image matric
sizeY = size(I,1);
sizeX = size(I,2);
J = zeros( sizeY + padSize*2, sizeX + padSize*2 );
% Fill in the original
J( (padSize+1):(padSize+sizeY) , (padSize+1):(padSize+sizeX) ) = I;
% Fill in areas above, below and to the sides or original
%top
J( 1:padSize, (padSize+1):(padSize+sizeX) ) = repmat(I(1,:),padSize,1);
%bottom
J( (padSize+sizeX+1):end, (padSize+1):(padSize+sizeX) ) = repmat(I(end,:),padSize,1);
%left
J( (padSize+1):(padSize+sizeY), 1:padSize ) = repmat(I(:,1),1,padSize);
%right
J( (padSize+1):(padSize+sizeY), (padSize+sizeY+1):end ) = repmat(I(:,end),1,padSize);
% Fill in the corners
J(1:padSize, 1:padSize) = I(1,1);
J((padSize+sizeY+1):end, 1:padSize) = I(end,1);
J(1:padSize, (padSize+sizeX+1):end) = I(1,end);
J((padSize+sizeY+1):end, (padSize+sizeX+1):end) = I(end,end);
Upvotes: 1