Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding an image in MATLAB

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');
like image 346
Sista Avatar asked Jul 06 '11 13:07

Sista


People also ask

How do I pad an image in Matlab?

B = padarray( A , padsize ) pads array A with an amount of padding in each dimension specified by padsize . The padarray function pads numeric or logical images with the value 0 and categorical images with the category <undefined> .

What does zero padding do to an image?

It means to enlarge the image by adding rectangular strips of zeros outside the rectangular edge of the image, so that you have a new larger rectangular image with a black frame around it.

How do you use zeros in Matlab?

X = zeros( sz ) returns an array of zeros where size vector sz defines size(X) . For example, zeros([2 3]) returns a 2-by-3 matrix. X = zeros(___, typename ) returns an array of zeros of data type typename . For example, zeros('int8') returns a scalar, 8-bit integer 0 .

How do you concatenate an array in Matlab?

You can use the square bracket operator [] to concatenate or append arrays. For example, [A,B] and [A B] concatenates arrays A and B horizontally, and [A; B] concatenates them vertically.


2 Answers

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.

like image 199
Aabaz Avatar answered Oct 22 '22 05:10

Aabaz


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;
like image 6
abcd Avatar answered Oct 22 '22 07:10

abcd