How to change the aspect ratio of an image in MATLAB?

I am new in MATLAB, I have the following code and I know that this code changes the image aspect ratio to 3:2 as it the writer says. I need to change the image to 4:3.
[h w] = size(img);
w = w*1.5;
newimg = imresize(img, [h w], 'nearest');
bit0 = bitand(newimg, uint8(ones(h,w)));
subplot(121), imshow(newimg);
subplot(122), imshow(bit0, [0 1]);

Answers (3)

You need to make the width 4/3 as big as the height. So you need to do
[oldHeight oldWidth oldNumberOfColorChannels] = size(img);
newWidth = int32(oldHeight * 4/3);
newImage = imresize(img, [oldHeight newWidth]);
and I don't know what the point of the ANDing stuff was - it's not related to your question at all.
Does this do what you want? Can you see the one line I changed?
[h w] = size(img);
w = w*4/3;
newimg = imresize(img, [h w], 'nearest');
bit0 = bitand(newimg, uint8(ones(h,w)));
subplot(121), imshow(newimg);
subplot(122), imshow(bit0, [0 1]);

4 Comments

That won't work unless the original image was square.
What part of it will fail? It is the same code as yours except that it uses 'nearest' .
My code makes the aspect ratio 4/3. The cyclist's code stretches the image by a ratio of 4/3. So his code doesn't necessarily end up with an aspect ratio of 4/3 unless the initial aspect ratio was 1. For example if the original image was 60 high by 600 wide (aspect ratio of 10), the new width would be 600*4/3 = 800. Since the height didn't change it's still 60 so the aspect ratio of the new image would be 13.33333, not 1.33333 as requested.

Sign in to comment.

I used the code that u gave me. but it now gives an error:
Warning: Size vector should be a row vector with integer elements. ??? Error using ==> bitand Matrix dimensions must agree.
doesn't work!

2 Comments

Just learn how to use the debugger. Set a breakpoint there and examine the size of the two images you're passing in to bitand().
I am going to speculate that that remark is directed to the cyclist. The code he presented is flawed in a couple of ways; Image Analyst's code is more robust.

Sign in to comment.

Categories

Find more on Deep Learning Toolbox in Help Center and File Exchange

Asked:

on 19 Dec 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!