Skip to content

Instantly share code, notes, and snippets.

@kingardor
Created December 10, 2020 10:36
Show Gist options
  • Save kingardor/24da6945b21b0a5ebaf92661c95c370c to your computer and use it in GitHub Desktop.
Save kingardor/24da6945b21b0a5ebaf92661c95c370c to your computer and use it in GitHub Desktop.
To resize and pad images
import cv2
import os
desired_size = (540,960)
path = ""
path2 = ""
files = os.listdir(path)
counter = 0
for f in files:
if not '.jpg' in f:
continue
im = cv2.imread(path+f)
old_size = im.shape[:2] # old_size is in (height, width) format
ratio = min(desired_size[0]/old_size[0],desired_size[1]/old_size[1])
new_size = tuple([int(x*ratio) for x in old_size])
# new_size should be in (width, height) format
im = cv2.resize(im, (new_size[1], new_size[0]))
delta_w = abs(desired_size[1] - new_size[1])
delta_h = abs(desired_size[0] - new_size[0])
top, bottom = delta_h//2, delta_h-(delta_h//2)
left, right = delta_w//2, delta_w-(delta_w//2)
color = [255, 255, 255]
# print(top, bottom, left, right)
new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT,
value=color)
cv2.imwrite(path2+f, new_im)
counter += 1
print(counter, end='\r')
# cv2.imshow("image", new_im)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment