Skip to content

Instantly share code, notes, and snippets.

@sftekin
Created December 20, 2019 12:53
Show Gist options
  • Save sftekin/d5ddf65e54e3dfe89a308c624e62280b to your computer and use it in GitHub Desktop.
Save sftekin/d5ddf65e54e3dfe89a308c624e62280b to your computer and use it in GitHub Desktop.
Example of torch.grid_sample. Warping implementation
"""
https://discuss.pytorch.org/t/solved-torch-grid-sample/51662
I have used this code.
"""
from torchvision import transforms
from PIL import Image
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
im_path = '11.jpg'
image = Image.open(im_path)
image = image.convert('RGB')
im_transform = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor()
])
image = im_transform(image)
# Add batch dimension
image = image.unsqueeze(dim=0)
d = torch.linspace(-1, 1, 224)
meshx, meshy = torch.meshgrid((d, d))
# Just to see the effect
meshx = meshx * 0.3
meshy = meshy * 0.9
grid = torch.stack((meshy, meshx), 2)
grid = grid.unsqueeze(0)
warped = F.grid_sample(image, grid, mode='bilinear', align_corners=False)
to_image = transforms.ToPILImage()
to_image(image.squeeze()).show()
to_image(warped.squeeze()).show(title='WARPED')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment