How to resize the image canvas to maintain a square aspect ratio

+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 by charlie_brown
• 7,710 points
146 views

2 answers to this question.

+1 vote
Best answer

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

answered Apr 4, 2018 by charlie_brown
• 7,710 points

selected Oct 12, 2018 by Omkar
0 votes

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

def resizeAndPad(img, size, padColor=255):

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
    pad_left, pad_right = np.floor(pad_horz).astype(int), np.ceil(pad_horz).astype(int)
    pad_top, pad_bot = 0, 0

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
    pad_top, pad_bot = np.floor(pad_vert).astype(int), np.ceil(pad_vert).astype(int)
    pad_left, pad_right = 0, 0

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

# scale and pad
scaled_img = cv2.resize(img, (new_w, new_h), interpolation=interp)
scaled_img = cv2.copyMakeBorder(scaled_img, pad_top, pad_bot, pad_left, pad_right, borderType=cv2.BORDER_CONSTANT, value=padColor)

return scaled_img
answered Oct 12, 2018 by findingbugs
• 4,750 points

Related Questions In Python

0 votes
1 answer

How to resize image canvas to maintain square aspect ratio in Python, OpenCv

Building on Alexander-Reynolds answer above, here is ...READ MORE

answered Sep 4, 2018 in Python by Priyaj
• 56,160 points
1,026 views
0 votes
1 answer

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

answered Apr 17, 2018 in Python by anonymous
26 views
0 votes
2 answers

How to calculate square root of a number in python?

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

answered Apr 2 in Python by anonymous
138 views
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
56 views
–1 vote
2 answers

How to find the size of a string in Python?

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

answered Mar 29 in Python by rajesh
• 1,210 points
59 views
0 votes
1 answer

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

You don't need to change your existing ...READ MORE

answered Dec 3, 2018 in Python by Nymeria
• 3,500 points

edited Dec 19, 2018 by Nymeria 6,535 views
0 votes
1 answer

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

answered Dec 19, 2018 in Python by Shuvodip
65 views
0 votes
1 answer

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

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

answered Jan 2 in Python by Omkar
• 67,120 points
16 views
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,710 points
1,079 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,710 points
43 views