Reputation: 935
I have an image of size 260 x 260
pixels. I know how to resize it to 140 x 140
pixels for example and then convert it to grayscale. Let us assume the matlab code below:
image = imread('my_image.jpg');
image_resized = imresize(image, [140 140]);
size(image_resized) % 140 x 140 x 3
image_gray = rgb2gray(image_resized);
size(image_gray) % 140 x 140
What I want is a specific case. I am interested to normalize the image to 140 pixels in height where width was rescaled accordingly so that the image aspect ratio was preserved. Unfortunately I don't know how to edit my above code.
Any help will be very appreciated.
Upvotes: 1
Views: 1455
Reputation: 221564
Try this -
image = imread('my_image.jpg');
desired_height = 140;
%%// Width of the resized image keeping the aspect ratio same as before
n2 = round((size(image,2)/size(image,1))*desired_height);
%%// Resized image
image_resized = imresize(image, [desired_height n2]);
Edit 1
NOTE: Alternatively you can use the size prescribed by imresize
using NaN as suggested by Shai's solution too, but it ceils or rounds up the sizes, which you might not want in most of the cases.
To prove this case, I tried imresize
to keep the height as 173, I got different sizes with manual resizing as opposed to when I let imresize
decide the sizes.
Code used for the experiment
%%// Resized image
image_resized_with_auto_sizing = imresize(image, [desired_height NaN]);
image_resized_with_manual_sizing = imresize(image, [desired_height n2]);
The size outputs for my experiment -
>> whos image_resized_with_manual_sizing image_resized_with_auto_sizing
Name Size Bytes Class Attributes
image_resized_with_auto_sizing 173x185x3 96015 uint8
image_resized_with_manual_sizing 173x184x3 95496 uint8
Notice the difference in width for the two cases. This issue is discussed here too.
Upvotes: 1
Reputation: 114796
You can use NaN
is the desired size argument to indicate exacty what you want
image_resized = imresize( image, [140 NaN] );
Which basically tells Matlab "don't bother me with the image's width - figure it out yourself!".
See imresize
documentation for more information.
Upvotes: 2