Skip to content

Instantly share code, notes, and snippets.

@ankitshekhawat
Last active May 7, 2019 12:24
Show Gist options
  • Save ankitshekhawat/df9817fdbdff200dcdd5860cac52c0e2 to your computer and use it in GitHub Desktop.
Save ankitshekhawat/df9817fdbdff200dcdd5860cac52c0e2 to your computer and use it in GitHub Desktop.
Resize and place an image in a square with padding.
#PIL method
from PIL import Image
def letterbox(image, size=299, bg=(0,0,0)):
(w,h) = image.size
ratio = size / max([w,h])
image = image.resize((int(ratio*w),int(ratio*h)))
background = Image.new('RGB', (size, size), bg)
background.paste(image, [int((size-s)/2) for s in image.size])
return background
#numpy method cv2 method
import cv2
import numpy as np
def letterbox_np(image, size=299., bg=0):
(w, h) = image.shape[:2]
ratio = size / max([w,h])
resized = cv2.resize(image, (int(ratio*w),int(ratio*h)))
pad_x, pad_y = [int(size-s) for s in resized.shape[:2]]
return np.pad(resized,
((int(pad_x/2),int(pad_x/2)+pad_x%2),(int(pad_y/2),int(pad_y/2)+pad_y%2),(0,0)),
mode='constant',
constant_values=bg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment