#!/usr/bin/env python3
import argparse
from pathlib import Path
import tensorflow as tf
from PIL import Image
def load_img(path_to_img, max_dim=512):
"""Load and resize an image to have max side length = max_dim."""
img = tf.io.read_file(str(path_to_img))
img = tf.image.decode_image(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32) # [0,1]
shape = tf.cast(tf.shape(img)[:-1], tf.float32)
long_dim = tf.reduce_max(shape)
scale = max_dim / long_dim
new_shape = tf.cast(shape * scale, tf.int32)
img = tf.image.resize(img, new_shape)
img = img[tf.newaxis, :] # add batch dimension
return img
def tensor_to_image(tensor):
"""Convert a [1,H,W,3] float32 tensor in [0,1] to a PIL image."""
tensor = tensor * 255.0
tensor = tf.clip_by_value(tensor, 0.0, 255.0)
tensor = tf.cast(tensor, tf.uint8)
if tensor.ndim > 3:
tensor = tf.squeeze(tensor, axis=0)
return Image.fromarray(tensor.numpy())
def vgg_layers(layer_names):
"""Create a VGG19 model that returns a list of intermediate outputs."""
vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')
vgg.trainable = False
outputs = [vgg.get_layer(name).output for name in layer_names]
model = tf.keras.Model([vgg.input], outputs)
return model
def gram_matrix(input_tensor):
"""Compute Gram matrix of a feature map."""
# input_tensor: [batch, height, width, channels]
result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor)
h = tf.shape(input_tensor)[1]
w = tf.shape(input_tensor)[2]
num_locations = tf.cast(h * w, tf.float32)
return result / num_locations
class StyleContentModel(tf.keras.models.Model):
def __init__(self, style_layers, content_layers):
super().__init__()
self.vgg = vgg_layers(style_layers + content_layers)
self.style_layers = style_layers
self.content_layers = content_layers
self.num_style_layers = len(style_layers)
self.vgg.trainable = False
def call(self, inputs):
# Expects float32 [0,1]
inputs = inputs * 255.0
preprocessed = tf.keras.applications.vgg19.preprocess_input(inputs)
outputs = self.vgg(preprocessed)
style_outputs = outputs[:self.num_style_layers]
content_outputs = outputs[self.num_style_layers:]
style_outputs = [gram_matrix(o) for o in style_outputs]
style_dict = {name: value
for name, value in zip(self.style_layers, style_outputs)}
content_dict = {name: value
for name, value in zip(self.content_layers, content_outputs)}
return {"style": style_dict, "content": content_dict}
def run_style_transfer(
content_path,
style_path,
output_path,
max_dim=512,
epochs=10,
steps_per_epoch=100,
style_weight=1e-2,
content_weight=1e4,
tv_weight=30.0,
):
# Load images
content_image = load_img(content_path, max_dim=max_dim)
style_image = load_img(style_path, max_dim=max_dim)
# Define which VGG layers to use
style_layers = [
'block1_conv1',
'block2_conv1',
'block3_conv1',
'block4_conv1',
'block5_conv1',
]
content_layers = ['block5_conv2']
extractor = StyleContentModel(style_layers, content_layers)
style_targets = extractor(style_image)['style']
content_targets = extractor(content_image)['content']
# Initialize generated image as content image
image = tf.Variable(content_image)
opt = tf.keras.optimizers.Adam(
learning_rate=0.02, beta_1=0.99, epsilon=1e-1
)
@tf.function
def train_step(image_var):
with tf.GradientTape() as tape:
outputs = extractor(image_var)
style_outputs = outputs['style']
content_outputs = outputs['content']
style_loss = tf.add_n([
tf.reduce_mean((style_outputs[name] - style_targets[name]) ** 2)
for name in style_outputs.keys()
])
style_loss *= style_weight / extractor.num_style_layers
content_loss = tf.add_n([
tf.reduce_mean((content_outputs[name] - content_targets[name]) ** 2)
for name in content_outputs.keys()
])
content_loss *= content_weight / len(content_layers)
tv_loss = tv_weight * tf.reduce_sum(tf.image.total_variation(image_var))
loss = style_loss + content_loss + tv_loss
grad = tape.gradient(loss, image_var)
opt.apply_gradients([(grad, image_var)])
image_var.assign(tf.clip_by_value(image_var, 0.0, 1.0))
return loss
step = 0
for epoch in range(epochs):
for _ in range(steps_per_epoch):
step += 1
loss = train_step(image)
if step % 50 == 0:
tf.print("Step", step, "Loss", loss)
result = tensor_to_image(image)
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
result.save(output_path)
print(f"Saved stylized image to: {output_path}")
def parse_args():
parser = argparse.ArgumentParser(
description="Neural style transfer using TensorFlow and VGG19."
)
parser.add_argument("--content", required=True, help="Path to content image")
parser.add_argument("--style", required=True, help="Path to style image")
parser.add_argument("--output", default="stylized.png", help="Output image path")
parser.add_argument("--max-dim", type=int, default=512,
help="Max dimension (longest side) of images")
parser.add_argument("--epochs", type=int, default=10,
help="Number of epochs")
parser.add_argument("--steps-per-epoch", type=int, default=100,
help="Optimization steps per epoch")
parser.add_argument("--style-weight", type=float, default=1e-2,
help="Weight for style loss")
parser.add_argument("--content-weight", type=float, default=1e4,
help="Weight for content loss")
parser.add_argument("--tv-weight", type=float, default=30.0,
help="Weight for total variation (smoothness) loss")
return parser.parse_args()
def main():
args = parse_args()
run_style_transfer(
content_path=args.content,
style_path=args.style,
output_path=args.output,
max_dim=args.max_dim,
epochs=args.epochs,
steps_per_epoch=args.steps_per_epoch,
style_weight=args.style_weight,
content_weight=args.content_weight,
tv_weight=args.tv_weight,
)
if __name__ == "__main__":
main()