Created
July 7, 2018 05:35
-
-
Save ceshine/1a3fd3a4fdad72daea840d8409eff385 to your computer and use it in GitHub Desktop.
Resize and Pad the image to Square Size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from torchvision import transforms | |
from PIL import ImageOps | |
class ResizeAndPad(object): | |
def __init__(self, size, interpolation=Image.BILINEAR): | |
assert isinstance(size, int) | |
self.size = size | |
self.interpolation = interpolation | |
def __call__(self, img): | |
w, h = img.size | |
if w > h: | |
ow = self.size | |
oh = int(self.size * h / w) | |
else: | |
ow = int(self.size * w / h) | |
oh = self.size | |
img = img.resize((ow, oh), self.interpolation) | |
delta_w = self.size - ow | |
delta_h = self.size - oh | |
padding = ( | |
delta_w//2, delta_h//2, | |
delta_w - (delta_w//2), | |
delta_h-(delta_h//2)) | |
img = ImageOps.expand(img, padding) | |
return img | |
def __repr__(self): | |
interpolate_str = transform._pil_interpolation_to_str[self.interpolation] | |
return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment