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

0 votes
I'd like to get a 1000 x 1000 picture in Python from any input picture so that the input doesn't lost it's aspect ratio. With 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 become 1000 x 1000 square. The original must be in the center at the end.
Sep 4, 2018 in Python by bug_seeker
• 15,520 points
4,789 views

1 answer to this question.

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 Sep 4, 2018 by Priyaj
• 58,090 points

Related Questions In Python

+1 vote
2 answers

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

down voteacceptedUsing OpenCVYou can use resize() in OpenCV to ...READ MORE

answered Apr 4, 2018 in Python by charlie_brown
• 7,720 points

edited Jul 11, 2023 by Khan Sarfaraz 1,252 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,313 views
0 votes
1 answer

How to save Numpy array as image in python?

If you have matplotlib, you can do: import ...READ MORE

answered Nov 16, 2018 in Python by Nymeria
• 3,560 points
8,556 views
0 votes
1 answer

How to resolve the error while importing cv2 from openCV in python?

I would recommend you go with anaconda ...READ MORE

answered Jul 31, 2019 in Python by Mohammad
• 3,230 points
1,668 views
0 votes
1 answer

How can I Get Laplacian pyramid using opencv

As far as I can see you ...READ MORE

answered Sep 4, 2018 in Python by Priyaj
• 58,090 points
1,703 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 58,090 points
1,189 views
0 votes
3 answers

How to get the current time in Python

FOLLOWING WAY TO FIND CURRENT TIME IN ...READ MORE

answered Apr 8, 2019 in Python by rajesh
• 1,270 points
1,673 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