Last active
May 5, 2019 14:07
-
-
Save KushajveerSingh/e9899522ee5f503c84cde34fcf75bd80 to your computer and use it in GitHub Desktop.
Load images and show resutls
This file contains 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
content_img = load_image(os.path.join(args.img_root, args.content_img), size=500) | |
content_img = content_img.to(device) | |
style_img = load_image(os.path.join(args.img_root, args.style_img)) | |
style_img = style_img.to(device) | |
# Show content and style image | |
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) | |
ax1.imshow(im_convert(content_img)) | |
ax2.imshow(im_convert(style_img)) | |
plt.show() | |
# Utility functions | |
def im_convert(img): | |
""" | |
Convert img from pytorch tensor to numpy array, so we can plot it. | |
It follows the standard method of denormalizing the img and clipping | |
the outputs | |
Input: | |
img :- (batch, channel, height, width) | |
Output: | |
img :- (height, width, channel) | |
""" | |
img = img.to('cpu').clone().detach() | |
img = img.numpy().squeeze(0) | |
img = img.transpose(1, 2, 0) | |
img = img * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406)) | |
img = img.clip(0, 1) | |
return img | |
def load_image(path, size=None): | |
""" | |
Resize img to size, size should be int and also normalize the | |
image using imagenet_stats | |
""" | |
img = Image.open(path) | |
if size is not None: | |
img = img.resize((size, size)) | |
transform = transforms.Compose([ | |
transforms.ToTensor(), | |
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) | |
]) | |
img = transform(img).unsqueeze(0) | |
return img |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment