I have to resize images in such a way that :-
1.) ratio should be constant (but small variations are acceptable)
2.) resultant image should have total number of pixels in given range
My pseudo algorithm is as follows:- (Total Pixels should be between 28000 & 30000 demonstrated in algorithm)
ratio=width/height
for i in range(width):
for j in range(height):
if (i!=0)|(j!=0):
no_of_pixels=i*j
if (no_of_pixels>=28000)*(no_of_pixels<=30000):
new_ratio=i/j
if abs(new_ratio-ratio)<=0.006:
new_width=i
new_height=j
My pseudo algorithm works properly but issue is that it is clearly not efficient. Is there any better way to speed it up?
CodePudding user response:
Just find the existing area and calculate how much you should reduce (or enlarge) it:
import math
area = width * height
factor = math.sqrt(30000.0 / float(area))
new_width = int(width * factor)
new_height = int(height * factor)