matlabperformancezero-pad

Efficient and fast way to padarray matrix


I tried to padarray more than 1000 images. However when I time my code, this specific line take the highest amount of time to complete

I=abs(padarray(I, [2, 2], 'replicate', 'both'));

Mainly because of the line 35 of the padarray algorithm (inside profiler): images\private\padarray_algo

b = a(aIdx{:});

Any way to improve the efficiency? Perhaps using another method? Thanks!


Solution

  • You can use repmat and matrix concatenation to get the same result:

    r=@repmat;
    pad=@(I,d)[r(I(1),d)    r(I(1,:),d(1),1)   r(I(1,end),d)
           r(I(:,1),1,d(2)) I                  r(I(:,end),1,d(2))
           r(I(end,1),d)    r(I(end,:),d(1),1) r(I(end),d)];
    

    Usage:

    pad(I,[2 2])
    

    If all images are of the same size you can create a matrix of linear indices of the image and apply padarray to it then use padded index array to pad images:

    %create matrix of indices
    Idx = reshape(1:numel(I),size(I));
    %pad the index
    Idx_padded = padarray(Idx, [2, 2], 'replicate', 'both'); 
    %use the padded index to pad images
    result = I(Idx_padded);
    result2 = I2(Idx_padded);