Learn practical skills, build real-world projects, and advance your career
!pip install jovian --upgrade --quiet

#Introduction

This tutorial explains how to implement the Neural-Style algorithm developed by Leon A. Gatys, Alexander S. Ecker and Matthias Bethge. Neural-Style, or Neural-Transfer, allows you to take an image and reproduce it with a new artistic style. The algorithm takes three images, an input image, a content-image, and a style-image, and changes the input to resemble the content of the content-image and the artistic style of the style-image.

#Underlying Principle

The principle is simple: we define two distances, one for the content (DC) and one for the style (DS). DC measures how different the content is between two images while DS measures how different the style is between two images. Then, we take a third image, the input, and transform it to minimize both its content-distance with the content-image and its style-distance with the style-image. Now we can import the necessary packages and begin the neural transfer.

#Importing Packages and Selecting a Device

Below is a list of the packages needed to implement the neural transfer.

  • torch, torch.nn, numpy (indispensables packages for neural networks with PyTorch)
  • torch.optim (efficient gradient descents)
  • PIL, PIL.Image, matplotlib.pyplot (load and display images)
  • torchvision.transforms (transform PIL images into tensors)
  • torchvision.models (train or load pre-trained models)
  • copy (to deep copy the models; system package)
from __future__ import print_function

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

from PIL import Image
import matplotlib.pyplot as plt
from IPython.display import Image
from skimage import io, transform

import torchvision.datasets as datasets
import torchvision.transforms as transforms
import torchvision.models as models
from torch.utils.data import DataLoader, Dataset
from torchvision.utils import make_grid
from torchvision.utils import save_image

import os
import glob
import numpy as np
import random
import copy

%matplotlib inline