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,720 points
1,645 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,720 points

edited Jul 11, 2023 by Khan Sarfaraz
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,780 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
• 58,020 points
5,197 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
902 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, 2019 in Python by anonymous
5,858 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 aryya
• 7,460 points
1,373 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, 2019 in Python by rajesh
• 1,270 points
2,107 views
0 votes
3 answers

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

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

answered Dec 15, 2020 in Python by Roshni
• 10,480 points
107,746 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 20, 2018 in Python by Shuvodip
796 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, 2019 in Python by Omkar
• 69,220 points
2,866 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,720 points
4,903 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,720 points
1,413 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP