The user wants a Python script for style transfer on images.
Style transfer involves taking a content image and a style image and combining them so the content image looks like it was painted in the style of the style image.
There are two main approaches to doing this in Python today:
Optimization-based (Slow, Classic): Using a pre-trained VGG19 network and optimizing pixel values to minimize content loss and style loss. This is what the original Gatys et al. paper did. It's good for understanding the concept but slow for practical use.
Feed-forward / Transformer Networks (Fast): Using models trained to perform style transfer instantly (e.g., Johnson et al.). This is much better for scripts where you want results quickly.
Libraries: Using high-level libraries like fast-style-transfer or PyTorch Hub / TensorFlow Hub models.
Given the prompt is general ("Create a Python script"), the best approach is to provide a script using PyTorch because it's the standard for this type of task right now, utilizing a pre-trained model from PyTorch Hub for ease of use and speed. Writing the optimization loop from scratch (Gatys method) is too long and complex for a simple "script" request unless specifically asked for.
However, often when people ask for this, they want to see the "magic" happen. Let's stick to the standard Gatys et al. algorithm (optimization) because it doesn't require downloading large separate model weights files manually (it uses standard VGG19 weights available in torchvision) and explains the core concept, OR use a modern pre-trained Transformer.
Let's look at the constraints.
Simplicity: The script should be easy to run.
Dependencies: Minimize weird dependencies. PyTorch and torchvision are standard.
Option A: The Optimization Approach (Gatys)
Pros: Works on any style without training a new model.
Cons: Slow (takes minutes per image).
Option B: The Pre-trained Transformer Approach (e.g., AdaIN or fast-neural-style)
Pros: Fast (milliseconds).
Cons: Usually restricted to specific styles the model was trained on, or requires downloading a specific .pth file from a GitHub repo.
I will provide the Optimization Approach (Option A) because it is "Universal" style transfer (works on any content and any style image provided at runtime) without needing to train a model beforehand. This is usually what users expect when they want to input two images and get a result.
Content Loss: MSE between content features and target features.
Style Loss: Gram Matrix comparison.
Optimizer: LBFGS is usually better for style transfer, but Adam is easier to code. I'll stick to Adam for simplicity or LBFGS for quality. Let's go with Adam for code readability, or standard Gradient Descent.
Main Loop: Iterate N times, calculate losses, backprop, update the input image (not the model weights).
Post-processing: Denormalize and save.
Drafting the Code (Mental Check):
Device selection (GPU/CPU).
get_image_optimizer function.
vgg model setup.
gram_matrix function.
Layers selection: Which layers for content? Usually Conv4_2. Which for style? Conv1_1, Conv2_1, etc.
Refining the prompt response:
I should provide a complete, runnable script. I will use PyTorch. I will add comments explaining the Gram matrix and the losses.
Step-by-step implementation details:
Load Images: Needs to handle different sizes. Scale style image to content image size? Or just scale both to a fixed max size? Fixed max size (e.g., 400px) is safer for memory.
VGG19: Use torchvision.models.vgg19(pretrained=True).features. Set .eval().
Feature Extraction: Need a way to hook into specific layers.
The Loop:
Target image = clone of content image (or white noise). Cloning content converges faster.
Optimizer: optim.Adam([target], lr=0.003).
Loop steps: Get features, calc content loss, calc style loss (sum over layers), combine, backward.
Self-Correction during drafting:
The optimization approach is slow. If the user runs this on a CPU, it will take a long time. I must explicitly mention GPU usage.
Is there a faster way? Yes, cv2 isn't for deep learning. fast-style-transfer repo is popular.
Actually, providing a script that implements the algorithm from scratch is the most educational and "universal" answer.
Let's write the script using PyTorch with the Gatys algorithm (Optimization).
Script Structure:
Imports.
load_image function.
im_convert (tensor to numpy) for display/save.
get_features (extract layers).
gram_matrix function.
Main execution block.
Requirements:torch, torchvision, pillow, matplotlib (for optional display), opencv-python (optional, let's stick to PIL to keep it lean).
I will ensure the code is modular so the user can easily change the content/style paths.
Wait, consider the "Fast Neural Style Transfer" option.
The optimization method takes 5-10 minutes on CPU.
Is there a PyTorch Hub module?
Yes, torch.hub.load('pytorch/vision:v0.10.0', 'model', ...) usually loads classifiers, not style transfer models directly without specific weights.
However, standard practice for a "create a script" request without specifying speed is the Gatys method because it allows arbitrary style images.
I will stick to the Optimization method (Neural Style Transfer algorithm) but optimize the code for clarity.
The Code:
Define image paths.
Define device.
Transformations.
Load VGG.
Extract features for Content and Style images (static).
Loop: Update Target image.
Save Target image.
Key technical details to get right:
The VGG network is frozen. We optimize the input image.
Use requires_grad_(True) on the target image.
Normalization is crucial for VGG.
Let's write the solution.
This task is best accomplished using PyTorch and the VGG19 model, which is the standard architecture for Neural Style Transfer (originally introduced by Gatys et al.).
This script implements the Optimization-based Style Transfer method. It takes a Content Image and a Style Image, then iteratively updates a Target Image to minimize the difference in content with the former and the difference in style (textures, colors) with the latter.
Prerequisites
You will need to install PyTorch, torchvision, and Pillow:
bash
pip install torch torchvision pillow
Python Script (style_transfer.py)
Save the following code into a file named style_transfer.py.
python
How to use this script:
Prepare Images: Find two images.
One Content Image (e.g., a photo of your dog). Save it as content.jpg.
One Style Image (e.g., "Starry Night" by Van Gogh). Save it as style.jpg.
Run: Execute the script:
bash
python style_transfer.py
Result: The script will print the progress. Once finished, it creates output.jpg which combines the content of the first image with the artistic style of the second.
Key Parameters to Tweak:
WEIGHT_STYLE (default 1e6): Increase this (e.g., 1e7) if the result looks too much like the original photo. Decrease it (e.g., 1e4) if the result looks too messy and loses the photo structure.
STEPS (default 3000): More steps generally mean better quality, but it takes longer. You can often see a good result after 500-1000 steps.
IMSIZE: Automatically set to 512 for GPU and 128 for CPU. You can manually set this higher if you have a powerful GPU and want a high-resolution output.
import torch
import torch.optim as optim
from torchvision import transforms, models
from PIL import Image
import copy
import os
# Configuration
IMSIZE = 512 if torch.cuda.is_available() else 128 # Use smaller size on CPU
CONTENT_IMAGE_PATH = 'content.jpg' # Replace with your image path
STYLE_IMAGE_PATH = 'style.jpg' # Replace with your image path
OUTPUT_PATH = 'output.jpg'
STEPS = 3000 # Number of optimization steps
WEIGHT_CONTENT = 1 # Weight for content loss
WEIGHT_STYLE = 1e6 # Weight for style loss (usually much higher)
# Select device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Running on device: {device}")
# 1. Image Loading and Preprocessing
# VGG networks are trained on images with each channel normalized by mean=[0.485, 0.456, 0.406]
# and std=[0.229, 0.224, 0.225].
loader = transforms.Compose([
transforms.Resize((IMSIZE, IMSIZE)), # Scale images to same size
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
def image_loader(image_name):
image = Image.open(image_name)
# Fake batch dimension required to fit network's input dimensions
image = loader(image).unsqueeze(0)
return image.to(device, torch.float)
# 2. Post-processing for display/saving
def tensor_to_image(tensor):
# Clone the tensor so we don't change it in-place
image = tensor.to("cpu").clone()
# Remove the fake batch dimension
image = image.squeeze(0)
# Denormalize
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
image = image * std + mean
# Clip values to valid range [0, 1]
image.clamp_(0, 1)
return transforms.ToPILImage()(image)
# 3. Load Model (VGG19)
cnn = models.vgg19(pretrained=True).features.to(device).eval()
# 4. Loss Mechanics
def gram_matrix(input):
batch_size, h, w, f_map_num = input.size() # batch size(=1)
# b=number of feature maps
# (h,w)=dimensions of a feature map (N=c*h*w)
features = input.view(batch_size * h, w * f_map_num) # resise F_XL into \hat F_XL
G = torch.mm(features, features.t()) # compute the gram product
# we 'normalize' the values of the gram matrix
# by dividing by the number of element in each feature maps.
return G.div(batch_size * h * w * f_map_num)
class ContentLoss(torch.nn.Module):
def __init__(self, target,):
super(ContentLoss, self).__init__()
# we 'detach' the target content from the tree used
# to dynamically compute the gradient: this is a stated value,
# not a variable. Otherwise the forward method of the criterion
# will throw an error.
self.target = target.detach()
def forward(self, input):
self.loss = torch.nn.functional.mse_loss(input, self.target)
return input
class StyleLoss(torch.nn.Module):
def __init__(self, target_feature):
super(StyleLoss, self).__init__()
self.target = gram_matrix(target_feature).detach()
def forward(self, input):
G = gram_matrix(input)
self.loss = torch.nn.functional.mse_loss(G, self.target)
return input
# 5. Model Construction
# Create a new Sequential model that inserts ContentLoss and StyleLoss modules
# after specific convolutional layers.
# Desired depth layers to compute style/content losses :
content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
def get_style_model_and_losses(cnn, style_img, content_img,
content_layers=content_layers_default,
style_layers=style_layers_default):
cnn = copy.deepcopy(cnn)
# Normalization module to normalize input images
normalization = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)).to(device)
# just in order to have an iterable access to or list of content/syle losses
content_losses = []
style_losses = []
model = torch.nn.Sequential(normalization)
i = 0 # increment every time we see a conv
for layer in cnn.children():
if isinstance(layer, torch.nn.Conv2d):
i += 1
name = f'conv_{i}'
elif isinstance(layer, torch.nn.ReLU):
name = f'relu_{i}'
# The in-place version works very well for very standardized
# models (like VGG), but it causes errors if we try to perform
# operations on the outputs. We replace it with the out-of-place version.
layer = torch.nn.ReLU(inplace=False)
elif isinstance(layer, torch.nn.MaxPool2d):
name = f'pool_{i}'
elif isinstance(layer, torch.nn.BatchNorm2d):
name = f'bn_{i}'
else:
raise RuntimeError(f'Unrecognized layer: {layer.__class__.__name__}')
model.add_module(name, layer)
if name in content_layers:
# add content loss:
target = model(content_img).detach()
content_loss = ContentLoss(target)
model.add_module(f"content_loss_{i}", content_loss)
content_losses.append(content_loss)
if name in style_layers:
# add style loss:
target_feature = model(style_img).detach()
style_loss = StyleLoss(target_feature)
model.add_module(f"style_loss_{i}", style_loss)
style_losses.append(style_loss)
# Now we trim off the layers after the last content and style losses
for i in range(len(model) - 1, -1, -1):
if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
break
model = model[:(i + 1)]
return model, style_losses, content_losses
# 6. Main Execution Function
def run_style_transfer():
if not os.path.exists(CONTENT_IMAGE_PATH) or not os.path.exists(STYLE_IMAGE_PATH):
print("Please ensure 'content.jpg' and 'style.jpg' exist in the directory.")
return
print("Loading images...")
style_img = image_loader(STYLE_IMAGE_PATH)
content_img = image_loader(CONTENT_IMAGE_PATH)
print("Building model...")
model, style_losses, content_losses = get_style_model_and_losses(cnn, style_img, content_img)
# We want to optimize the input image, not the model parameters
optimizer = optim.LBFGS([content_img.requires_grad_()]) # Or use Adam
print("Optimizing...")
run = [0]
while run[0] <= STEPS:
def closure():
# correct the values of updated input image
content_img.data.clamp_(0, 1)
optimizer.zero_grad()
model(content_img)
style_score = 0
content_score = 0
for sl in style_losses:
style_score += sl.loss
for cl in content_losses:
content_score += cl.loss
style_score *= WEIGHT_STYLE
content_score *= WEIGHT_CONTENT
loss = style_score + content_score
loss.backward()
run[0] += 1
if run[0] % 50 == 0:
print(f"Step {run[0]}:")
print(f"Style Loss: {style_score.item():4f} Content Loss: {content_score.item():4f}")
return style_score + content_score
optimizer.step(closure)
# a last correction...
content_img.data.clamp_(0, 1)
print("Saving result...")
output_image = tensor_to_image(content_img)
output_image.save(OUTPUT_PATH)
print(f"Done! Saved to {OUTPUT_PATH}")
if __name__ == "__main__":
run_style_transfer()