Padding an image in MATLAB

2019-02-22 00:03发布

I have an image of size 61x56 and I want to pad the image to size 392x392.

I am trying to use padarray but since I get a non-integer value I am unable to do this. Can anyone help me with this. Thanks a lot! I have attached what I want to do below.

K = imread('test.jpg');
K = rgb2gray(K);
[m n] = size(K);
p = 392;
q = 392;
K_pad = padarray(K, [(p-m)/2 (q-n)/2], 'replicate');

3条回答
神经病院院长
2楼-- · 2019-02-22 00:39

You can divide your padarray instruction in two calls:

K_pad = padarray(K, [floor((p-m)/2) floor((q-n)/2)], 'replicate','post');
K_pad = padarray(K_pad, [ceil((p-m)/2) ceil((q-n)/2)], 'replicate','pre');

But you may want to check what is happening in the corners of the image to see if it is ok with what you want to do with it.

查看更多
【Aperson】
3楼-- · 2019-02-22 00:43

You can try this function:

function out1 = myresize(in1)
%% Sa1habibi@gmail.com
%% resize an image to closest power of 2

[m,n] = size(in1);

if(rem(m,2)~=0)
    in1(1,:)=[];
end

if(rem(n,2)~=0)
    in1(:,1)=[];
end

[m,n] = size(in1);

a = max(m,n);

if(log2(a)~=nextpow2(a) || m~=n)

    s1 = 2^nextpow2(a);
    n_row = (s1 - m)/2;
    n_col = (s1 - n)/2;

    dimension = [n_row,n_col];

    out1 = padarray(in1,dimension);

end
end

for example:

A = ones(2,8);
out1 = myresize(A);

first it finds the maximum of rows and columns, then paddarray the matrix in both direction.

查看更多
Fickle 薄情
4楼-- · 2019-02-22 00:45

Here's another way of padding it without using padarray.

imgSize=size(img); %#img is your image matrix
finalSize=392;   
padImg=zeros(finalSize);

padImg(finalSize/2+(1:imgSize(1))-floor(imgSize(1)/2),...
    finalSize/2+(1:imgSize(2))-floor(imgSize(2)/2))=img;
查看更多
登录 后发表回答