实现矩阵填充的最佳方法

时间:2013-10-25 22:36:46

标签: matlab matrix padding

我正在尝试在边框处填充一个用零填充的矩阵,其中像素的值最接近边框,例如:

A = rand(5);
Z = zeros(9);
Z(3:7, 3:7) = A;

enter image description here

现在我想以下列方式完成矩阵边界:

enter image description here

我正在寻找一个没有任何for循环的好解决方案

编辑:

它应该是这样的:

enter image description here

2 个答案:

答案 0 :(得分:5)

您希望padarray使用'replicate'选项。例如,要在所有方面复制2x2边框,

>> A = [1 2; 3 4];
>> B = padarray(A,[2 2],'replicate','both')
B =
     1     1     1     2     2     2
     1     1     1     2     2     2
     1     1     1     2     2     2
     3     3     3     4     4     4
     3     3     3     4     4     4
     3     3     3     4     4     4

答案 1 :(得分:1)

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