Ben
Ben

Reputation: 57

How to resize image by mainitaining aspect ratio in python3?

I have an image with image.shape=(20,10)and I want to resize this image so that new image size would be image.size = 90.

I want to use np.resize(image,(new_width, new_height)), but how can I calculate new_width and new_height, so that it maintains aspect_ratio as same as in original image.

Upvotes: 0

Views: 172

Answers (3)

Sxribe
Sxribe

Reputation: 829

You can use this simple function for finding the new height of an image with width as an input

def findHeight(original_width, original_height, new_width):
    area = original_width * original_height
    new_height = area/new_width
    return new_height

Upvotes: 0

Mark Setchell
Mark Setchell

Reputation: 207385

The height of your image is 20 and the width is 10, so the height is 2x the width, i.e.

h = 2 * w

You want your new image to have an area of 90 pixels, and the area (A) is:

A = h * w

90 = 2 * w * w

w = sqrt(45)

So the sides of your image need to be 6.7 and 13.4

I hope that helps, even if I doubt it will.

Upvotes: 0

Guimoute
Guimoute

Reputation: 4629

Well, you choose which dimension you want to enforce and then you adjust the other one by calculating either new_width = new_height*aspect_ratio or new_height = new_width/aspect_ratio.

You might want to round those numbers and convert them to int too.

Upvotes: 1

Related Questions