import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision.transforms as transforms
from PIL import Image
import torchvision.models as models
from torchvision.utils import save_image
import os
import sys
# Device configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# VGG19 model for feature extraction
class VGG19(nn.Module):
def __init__(self):
super(VGG19, self).__init__()
self.features = models.vgg19(pretrained=True).features.eval()
for param in self.parameters():
param.requires_grad = False
def forward(self, x):
return self.features(x)
# Image loading and preprocessing
def load_image(img_path, max_size=400, shape=None):
image = Image.open(img_path).convert('RGB')
# Resize
size = max_size if max(shape) > max_size else max(shape)
if max(image.size) > size:
image.thumbnail((size, size), Image.LANCZOS)
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
return transform(image).unsqueeze(0).to(device)
# Image unnormalization and saving
def imsave(tensor, path):
unnormalize = transforms.Normalize(
mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],
std=[1/0.229, 1/0.224, 1/0.225]
)
image = unnormalize(tensor[0].cpu())
image.clamp_(0, 1)
save_image(image, path)
# Gram matrix for style loss
def gram_matrix(input):
a, b, c, d = input.size()
features = input.view(a * b, c * d)
G = torch.mm(features, features.t())
return G.div(a * b * c * d)
# Content and Style losses
class ContentLoss(nn.Module):
def forward(self, input):
self.loss = nn.MSELoss()(input, self.target)
return input
class StyleLoss(nn.Module):
def gram_style(self):
return gram_matrix(self.target)
def forward(self, input):
G = gram_matrix(input)
self.loss = nn.MSELoss()(G, self.gram_style())
return input
# Total Variation Loss for smoothness
def total_variation_loss(img):
loss = torch.mean(torch.abs(img[:, :, :, :-1] - img[:, :, :, 1:])) + \
torch.mean(torch.abs(img[:, :, :-1, :] - img[:, :, 1:, :]))
return loss
def get_style_model_and_losses(cnn, style_img, content_img,
content_layers=['conv_4_2'],
style_layers=['conv_1_1', 'conv_2_1', 'conv_3_1', 'conv_4_1', 'conv_5_1']):
cnn = cnn.to(device).eval()
normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
content_losses = []
style_losses = []
i = 0
x = content_img.clone()
for layer in cnn.features:
if isinstance(layer, nn.Conv2d):
i += 1
name = f'conv_{i}'
elif isinstance(layer, nn.ReLU):
name = f'relu_{i}'
layer = nn.ReLU(inplace=False)
elif isinstance(layer, nn.MaxPool2d):
name = f'pool_{i}'
else:
raise RuntimeError(f'Unrecognized layer: {layer.__class__.__name__}')
x = layer(x)
if name in content_layers:
target = x.detach()
content_loss = ContentLoss()
content_loss.target = target
cnn.add_module(f"{name}_content", content_loss)
content_losses.append(name + '_content')
if name in style_layers:
target_feature = x.detach()
style_loss = StyleLoss()
style_loss.target = target_feature
cnn.add_module(f"{name}_style", style_loss)
style_losses.append(name + '_style')
# Remove non-differentiable modules
for i in range(len(cnn.features)):
if i == len(content_layers) + len(style_layers):
break
name = f'conv_{i+1}' if i+1 < 10 else f'conv_{i//10}_{i%10+1}'
if name in content_layers or name in style_layers:
continue
if isinstance(cnn.features._modules[name.split('_')[0]], nn.MaxPool2d):
cnn.features._modules[name.split('_')[0]] = nn.AvgPool2d(2, stride=2)
return cnn, style_losses, content_losses
def get_input_optimizer(input_img):
optimizer = optim.LBFGS([input_img.requires_grad_()])
return optimizer
def run_style_transfer(cnn, content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1, tv_weight=10,
save_every=100, output_dir='outputs'):
os.makedirs(output_dir, exist_ok=True)
optimizer = get_input_optimizer(input_img)
print('Optimizing...')
run = [0]
while run[0] <= num_steps:
def closure():
input_img.data.clamp_(0, 1)
optimizer.zero_grad()
# Forward pass
x = input_img.clone()
for module in cnn.children():
x = module(x)
# Compute losses
style_score = 0
content_score = 0
tv_score = 0
for sl in style_losses:
style_score += cnn._modules[sl].loss
for cl in content_losses:
content_score += cnn._modules[cl].loss
tv_score = total_variation_loss(input_img)
style_score *= style_weight
content_score *= content_weight
tv_score *= tv_weight
loss = style_score + content_score + tv_score
loss.backward()
run[0] += 1
if run[0] % 50 == 0:
print(f'Step: {run[0]}, Style Loss: {style_score.item():.4f}, '
f'Content Loss: {content_score.item():.4f}, '
f'TV Loss: {tv_score.item():.4f}')
if run[0] % save_every == 0:
imsave(input_img, os.path.join(output_dir, f'stylized_{run[0]}.png'))
return style_score + content_score + tv_score
optimizer.step(closure)
# Save final image
imsave(input_img, os.path.join(output_dir, 'final_stylized.png'))
print('Done! Check outputs/ directory for results.')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Neural Style Transfer')
parser.add_argument('--content', type=str, required=True, help='Path to content image')
parser.add_argument('--style', type=str, required=True, help='Path to style image')
parser.add_argument('--output_dir', type=str, default='outputs', help='Output directory')
parser.add_argument('--content_weight', type=float, default=1, help='Content weight')
parser.add_argument('--style_weight', type=float, default=1e6, help='Style weight')
parser.add_argument('--tv_weight', type=float, default=10, help='Total variation weight')
parser.add_argument('--num_steps', type=int, default=300, help='Number of optimization steps')
parser.add_argument('--save_every', type=int, default=100, help='Save image every N steps')
parser.add_argument('--max_size', type=int, default=400, help='Max image size for resizing')
args = parser.parse_args()
# Load images
content_img = load_image(args.content, max_size=args.max_size)
style_img = load_image(args.style, shape=content_img.shape[-2:])
# Initialize target image as content image
target_img = content_img.clone().requires_grad_(True)
# Load VGG19 and define losses
cnn = VGG19()
global style_losses, content_losses
cnn, style_losses, content_losses = get_style_model_and_losses(
cnn, style_img, content_img
)
# Run optimization
run_style_transfer(cnn, content_img, style_img, target_img,
num_steps=args.num_steps,
style_weight=args.style_weight,
content_weight=args.content_weight,
tv_weight=args.tv_weight,
save_every=args.save_every,
output_dir=args.output_dir)
Usage Instructions
-
Install dependencies:
pip install torch torchvision pillow
-
Run the script:
python style_transfer.py --content path/to/content.jpg --style path/to/style.jpg
- Optional:
--output_dir my_outputs --num_steps 500 --style_weight 1000000
- Images will be resized if larger than
--max_size (default 400px).
-
Output:
- Results saved in
outputs/ (or specified dir): stylized_100.png, stylized_200.png, ..., final_stylized.png.
Notes
- Based on PyTorch's neural style transfer tutorial.
- Uses LBFGS optimizer for faster convergence (GPU recommended).
- Adjust weights: higher
style_weight emphasizes style more.
- Tested on images like photos/paintings; works best with similar aspect ratios.