Skip to content

Instantly share code, notes, and snippets.

@gggauravgandhi
Last active May 21, 2020 21:01
Show Gist options
  • Select an option

  • Save gggauravgandhi/f28b602b4d040aa1d3f5fb1a17295c06 to your computer and use it in GitHub Desktop.

Select an option

Save gggauravgandhi/f28b602b4d040aa1d3f5fb1a17295c06 to your computer and use it in GitHub Desktop.
Resize image by maintaining aspect ratio with adding padding
import numpy as np
import PIL
from PIL import Image
def resize_image(np_img):
"""Resizes image with maintaining aspect ratio"""
# Convert numpy array image into Pillow format image
im = Image.fromarray(np_img)
# Find max size of an image
x, y = im.size
max_size = max(x, y)
# Draw black image and paste input image in middle
new_im = Image.new('RGBA', (max_size, max_size), (0, 0, 0))
new_im.paste(im, (int((max_size - x) / 2), int((max_size - y) / 2)))
# Resize the image
new_im = new_im.resize(
(cfg.image_width, cfg.image_height), PIL.Image.ANTIALIAS)
# np_resized_img = np.array(new_im)
# Convert to RGB and drop alpha channel
new_im = new_im.convert("RGB")
np_resized_img = np.asarray(new_im, dtype=np.float32) / 255
np_resized_img = np_resized_img[:, :, :3]
np_resized_img = np.array(np_resized_img, dtype=np.int)
return np_resized_img
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment