Reputation:
I want to extend the size my image using MATLAB. For example, I have an image of 397x450
I want to make it into 600x600
where I place the original image in the middle, but all of the new elements have to be 1
i.e. 397x450 elements will remain the same as original image and will be placed in the middle of the output image, and rest of the elements in 600x600
image will be made 1
.
Is there an efficient way to do this in MATLAB?
Upvotes: 1
Views: 519
Reputation: 104514
If you want to extend the image so that original contents are in the middle, you can calculate the middle of the output image which is initialized to all 1s, then make sure you place the image so that it spans the width and height of the original one. This will get messy if you have input images that are even in dimension... but assuming you have odd dimensions, do this:
rows_out = 600; cols_out = 600;
out = ones(rows_out, cols_out, size(im,3));
rows_in = size(im,1); cols_in = size(im,2);
rows_half = floor(rows_in/2); cols_half = floor(cols_in/2);
out_half_rows = floor(rows_out/2); out_half_cols = floor(cols_out/2);
out(out_half_rows-rows_half : out_half_rows+rows_half, ...
out_half_cols-cols_half : out_half_cols+cols_half, :) = im;
As an additional check, you can check to see if your image has even rows or columns by checking the remainder of dividing by 2 and if there is a reminder, we can remove the last row and/or column for example:
rows_in = size(im,1) - (mod(size(im,1),2) + 1);
cols_in = size(im,2) - (mod(size(im,2),2) + 1);
im = im(1:rows_in, 1:cols_in, :);
Take note that the above code will remove the last two rows and two columns for the case of it being odd.
Here's an example with a 256 x 256 dark square on a 600 x 600 white background:
out = ones(600,600);
im = zeros(256,256);
Using the above checks to ensure odd image sizes, we get:
Upvotes: 2