+1 vote

I'd like to get a 1000 x 1000 picture in Python from any input picture so that the input doesn't lose its aspect ratio. In other words, I want to resize the input so that its longer dimension be 1000 pixels and "fill" the other dimension with the background color until it becomes 1000 x 1000 square. The original must be in the center at the end.

Apr 4, 2018 in Python 1,473 views

## 2 answers to this question.

+1 vote

down voteacceptedUsing OpenCVYou can use resize() in OpenCV to resize the image up/down to the size you need. However, resize() requires that you put in either the destination size (in both dimensions) or the scaling (in both dimensions), so you can't just put one or the other in for 1000 and let it calculate the other for you. So the most robust way to do this is to find the aspect ratio and calculate what the smaller dimension would be when the bigger one is stretched to 1000. Then you can resize.

down voteaccepted

• 7,720 points

edited Jul 11, 2023

Building on Alexander-Reynolds answer above, here is the code that handles all possible sizes and situations.

```h, w = img.shape[:2]
sh, sw = size

# interpolation method
if h > sh or w > sw: # shrinking image
interp = cv2.INTER_AREA

else: # stretching image
interp = cv2.INTER_CUBIC

# aspect ratio of image
aspect = float(w)/h
saspect = float(sw)/sh

if (saspect > aspect) or ((saspect == 1) and (aspect <= 1)):  # new horizontal image
new_h = sh
new_w = np.round(new_h * aspect).astype(int)
pad_horz = float(sw - new_w) / 2

elif (saspect < aspect) or ((saspect == 1) and (aspect >= 1)):  # new vertical image
new_w = sw
new_h = np.round(float(new_w) / aspect).astype(int)
pad_vert = float(sh - new_h) / 2

if len(img.shape) is 3 and not isinstance(padColor, (list, tuple, np.ndarray)): # color image but only one color provided

scaled_img = cv2.resize(img, (new_w, new_h), interpolation=interp)

return scaled_img```
• 4,780 points

## How to hide a window in the constructor immediately after creation?

You can use QtCore.QTimer class Example(QWidget):     def __init__(self, app):         QWidget.__init__(self)         QTimer.singleShot(0, ...READ MORE

## How to calculate square root of a number in python?

calculate square root in python >>> import math ...READ MORE

–1 vote

## How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

## How to get the return value from a thread using python?

FWIW, the multiprocessing module has a nice interface for ...READ MORE

## I have a dictonary in python how to access the value field?

dic={"car":["limo","sedan"]} print (dic.keys())    <-----------------------Fetch the key "car" print (dic['car'][0])   <------------------------Fetch ...READ MORE

## How to print a message or the error if a file is not found?

To print the message that file is not ...READ MORE