How to change the aspect ratio of an image in MATLAB?
Show older comments
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)
Image Analyst
on 19 Dec 2011
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.
the cyclist
on 19 Dec 2011
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
Image Analyst
on 19 Dec 2011
That won't work unless the original image was square.
Walter Roberson
on 19 Dec 2011
What part of it will fail? It is the same code as yours except that it uses 'nearest' .
Image Analyst
on 20 Dec 2011
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.
Walter Roberson
on 20 Dec 2011
Makes sense now.
Amin
on 20 Dec 2011
0 votes
2 Comments
Image Analyst
on 20 Dec 2011
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().
Walter Roberson
on 20 Dec 2011
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.
Categories
Find more on Deep Learning Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!