How to resize an image in python, while retaining aspect ratio, given a target size?

2024/10/9 20:21:41

First off part of me feels like this is a stupid question, sorry about that. Currently the most accurate way I've found of calculating the optimum scaling factor (best width and height for target pixel count while retaining aspect ratio) is iterating through and choosing the best one however there must be a better way of doing this.

An example:

import cv2, numpy as np
img = cv2.imread("arnold.jpg")img.shape[1] # e.g. width  = 700
img.shape[0] # e.g. height = 979# e.g. Total  pixels : 685,300TARGET_PIXELS = 100000
MAX_FACTOR    = 0.9
STEP_FACTOR   = 0.001
iter_factor   = STEP_FACTOR
results       = dict()while iter_factor < MAX_RATIO:img2 = cv2.resize(img, (0,0), fx=iter_factor, fy=iter_factor)results[img2.shape[0]*img2.shape[1]] = iter_factoriter_factor += step_factorbest_pixels = min(results, key=lambda x:abs(x-TARGET_PIXELS))
best_ratio  = results[best_pixels]print best_pixels # e.g. 99750
print best_ratio  # e.g. 0.208

I know there are probably some errors lying around in the code above i.e. there is no check in the results dictionary for an existing key but I am more concerned with a different approach which I cannot figure out was looking into lagrangian optimisation but that seems quite complex also for a simple problem. Any ideas?

** EDIT AFTER ANSWER **

Going to provide the code if anyone is interested in the answer

import math, cv2, numpy as np# load up an image
img = cv2.imread("arnold.jpg")TARGET_PIXEL_AREA = 100000.0ratio = float(img.shape[1]) / float(img.shape[0])
new_h = int(math.sqrt(TARGET_PIXEL_AREA / ratio) + 0.5)
new_w = int((new_h * ratio) + 0.5)img2 = cv2.resize(img, (new_w,new_h))
Answer

Here is my approach,

aspectRatio = currentWidth / currentHeight
heigth * width = area

So,

height * (height * aspectRatio) = area
height² = area / aspectRatio
height = sqrt(area / aspectRatio)

At that point we know the target height, and width = height * aspectRatio.

Ex:

area = 100 000
height = sqrt(100 000 / (700/979)) = 373.974
width = 373.974 * (700/979) = 267.397
https://en.xdnf.cn/q/69974.html

Related Q&A

How to limit number of followed pages per site in Python Scrapy

I am trying to build a spider that could efficiently scrape text information from many websites. Since I am a Python user I was referred to Scrapy. However, in order to avoid scraping huge websites, I …

Why is Pythons sorted() slower than copy, then .sort()

Here is the code I ran:import timeitprint timeit.Timer(a = sorted(x), x = [(2, bla), (4, boo), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]).timeit(number = 1000) print timeit.Timer(a=x[:];a.sort(…

How to efficiently unroll a matrix by value with numpy?

I have a matrix M with values 0 through N within it. Id like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i.The solution below uses a lo…

Anaconda Python 3.6 -- pythonw and python supposed to be equivalent?

According to Python 3 documentation, python and pythonw should be equivalent for running GUI scripts as of 3.6With older versions of Python, there is one Mac OS X quirk that you need to be aware of: pr…

Good way of handling NoneType objects when printing in Python

How do I go about printin a NoneType object in Python?# score can be a NonType object logging.info("NEW_SCORE : "+score)Also why is that sometime I see a comma instead of the + above?

problems with easy_install pycrypto

Im trying install pycrypto on osx with easy_install and Im getting the following error:easy_install pycrypto Searching for pycrypto Reading http://pypi.python.org/simple/pycrypto/ Reading http://pycryp…

What is the most efficient way to do a sorted reduce in PySpark?

I am analyzing on-time performance records of US domestic flights from 2015. I need to group by tail number, and store a date sorted list of all the flights for each tail number in a database, to be re…

Interactive figure with OO Matplotlib

Using Matplotlib via the OO API is easy enough for a non-interactive backend:from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvasfrom matplotlib.figure import Figurefig = Figure(…

nose2 vs py.test with isolated processes

We have been using nosetest for running and collecting our unittests (which are all written as python unittests which we like). Things we like about nose:uses standard python unit tests (we like the st…

ValueError: Attempt to reuse RNNCell with a different variable scope than its first use

The following code fragmentimport tensorflow as tf from tensorflow.contrib import rnnhidden_size = 100 batch_size = 100 num_steps = 100 num_layers = 100 is_training = True keep_prob = 0.4input_da…