我正在尝试用最接近边界的像素处的值填充边界处用零填充的矩阵,例如:
A = rand(5);
Z = zeros(9);
Z(3:7, 3:7) = A;
现在我想通过以下方式完成矩阵边框:
我正在寻找一个没有任何 for 循环的好解决方案
编辑:
它应该如下所示:
你想要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
% 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);