Franco Astegiano commited on
Commit
6a17cc3
·
unverified ·
1 Parent(s): 46b5e1b

python file

Browse files
examples/colab/tf_hub_fast_style_transfer_for_arbitrary_styles.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """TF-Hub: Fast Style Transfer for Arbitrary Styles.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb
8
+
9
+ ##### Copyright 2019 The TensorFlow Hub Authors.
10
+
11
+ Licensed under the Apache License, Version 2.0 (the "License");
12
+ """
13
+
14
+ # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
15
+ #
16
+ # Licensed under the Apache License, Version 2.0 (the "License");
17
+ # you may not use this file except in compliance with the License.
18
+ # You may obtain a copy of the License at
19
+ #
20
+ # http://www.apache.org/licenses/LICENSE-2.0
21
+ #
22
+ # Unless required by applicable law or agreed to in writing, software
23
+ # distributed under the License is distributed on an "AS IS" BASIS,
24
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ # See the License for the specific language governing permissions and
26
+ # limitations under the License.
27
+ # ==============================================================================
28
+
29
+ """# Fast Style Transfer for Arbitrary Styles
30
+
31
+ <table class="tfo-notebook-buttons" align="left">
32
+ <td>
33
+ <a target="_blank" href="https://www.tensorflow.org/hub/tutorials/tf2_arbitrary_image_stylization"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
34
+ </td>
35
+ <td>
36
+ <a target="_blank" href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
37
+ </td>
38
+ <td>
39
+ <a target="_blank" href="https://github.com/tensorflow/hub/blob/master/examples/colab/tf2_arbitrary_image_stylization.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View on GitHub</a>
40
+ </td>
41
+ <td>
42
+ <a href="https://storage.googleapis.com/tensorflow_docs/hub/examples/colab/tf2_arbitrary_image_stylization.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
43
+ </td>
44
+ <td>
45
+ <a href="https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2"><img src="https://www.tensorflow.org/images/hub_logo_32px.png" />See TF Hub model</a>
46
+ </td>
47
+ </table>
48
+
49
+ Based on the model code in [magenta](https://github.com/tensorflow/magenta/tree/master/magenta/models/arbitrary_image_stylization) and the publication:
50
+
51
+ [Exploring the structure of a real-time, arbitrary neural artistic stylization
52
+ network](https://arxiv.org/abs/1705.06830).
53
+ *Golnaz Ghiasi, Honglak Lee,
54
+ Manjunath Kudlur, Vincent Dumoulin, Jonathon Shlens*,
55
+ Proceedings of the British Machine Vision Conference (BMVC), 2017.
56
+
57
+ ## Setup
58
+
59
+ Let's start with importing TF2 and all relevant dependencies.
60
+ """
61
+
62
+ import functools
63
+ import os
64
+
65
+ from matplotlib import gridspec
66
+ import matplotlib.pylab as plt
67
+ import numpy as np
68
+ import tensorflow as tf
69
+ import tensorflow_hub as hub
70
+
71
+ print("TF Version: ", tf.__version__)
72
+ print("TF Hub version: ", hub.__version__)
73
+ print("Eager mode enabled: ", tf.executing_eagerly())
74
+ print("GPU available: ", tf.config.list_physical_devices('GPU'))
75
+
76
+ # @title Define image loading and visualization functions { display-mode: "form" }
77
+
78
+ def crop_center(image):
79
+ """Returns a cropped square image."""
80
+ shape = image.shape
81
+ new_shape = min(shape[1], shape[2])
82
+ offset_y = max(shape[1] - shape[2], 0) // 2
83
+ offset_x = max(shape[2] - shape[1], 0) // 2
84
+ image = tf.image.crop_to_bounding_box(
85
+ image, offset_y, offset_x, new_shape, new_shape)
86
+ return image
87
+
88
+ @functools.lru_cache(maxsize=None)
89
+ def load_image(image_url, image_size=(256, 256), preserve_aspect_ratio=True):
90
+ """Loads and preprocesses images."""
91
+ # Cache image file locally.
92
+ image_path = tf.keras.utils.get_file(os.path.basename(image_url)[-128:], image_url)
93
+ # Load and convert to float32 numpy array, add batch dimension, and normalize to range [0, 1].
94
+ img = tf.io.decode_image(
95
+ tf.io.read_file(image_path),
96
+ channels=3, dtype=tf.float32)[tf.newaxis, ...]
97
+ img = crop_center(img)
98
+ img = tf.image.resize(img, image_size, preserve_aspect_ratio=True)
99
+ return img
100
+
101
+ def show_n(images, titles=('',)):
102
+ n = len(images)
103
+ image_sizes = [image.shape[1] for image in images]
104
+ w = (image_sizes[0] * 6) // 320
105
+ plt.figure(figsize=(w * n, w))
106
+ gs = gridspec.GridSpec(1, n, width_ratios=image_sizes)
107
+ for i in range(n):
108
+ plt.subplot(gs[i])
109
+ plt.imshow(images[i][0], aspect='equal')
110
+ plt.axis('off')
111
+ plt.title(titles[i] if len(titles) > i else '')
112
+ plt.show()
113
+
114
+ """Let's get as well some images to play with."""
115
+
116
+ # @title Load example images { display-mode: "form" }
117
+
118
+ content_image_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Golden_Gate_Bridge_from_Battery_Spencer.jpg/640px-Golden_Gate_Bridge_from_Battery_Spencer.jpg' # @param {type:"string"}
119
+ style_image_url = 'https://upload.wikimedia.org/wikipedia/commons/0/0a/The_Great_Wave_off_Kanagawa.jpg' # @param {type:"string"}
120
+ output_image_size = 384 # @param {type:"integer"}
121
+
122
+ # The content image size can be arbitrary.
123
+ content_img_size = (output_image_size, output_image_size)
124
+ # The style prediction model was trained with image size 256 and it's the
125
+ # recommended image size for the style image (though, other sizes work as
126
+ # well but will lead to different results).
127
+ style_img_size = (256, 256) # Recommended to keep it at 256.
128
+
129
+ content_image = load_image(content_image_url, content_img_size)
130
+ style_image = load_image(style_image_url, style_img_size)
131
+ style_image = tf.nn.avg_pool(style_image, ksize=[3,3], strides=[1,1], padding='SAME')
132
+ show_n([content_image, style_image], ['Content image', 'Style image'])
133
+
134
+ """## Import TF Hub module"""
135
+
136
+ # Load TF Hub module.
137
+
138
+ hub_handle = 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2'
139
+ hub_module = hub.load(hub_handle)
140
+
141
+ """The signature of this hub module for image stylization is:
142
+ ```
143
+ outputs = hub_module(content_image, style_image)
144
+ stylized_image = outputs[0]
145
+ ```
146
+ Where `content_image`, `style_image`, and `stylized_image` are expected to be 4-D Tensors with shapes `[batch_size, image_height, image_width, 3]`.
147
+
148
+ In the current example we provide only single images and therefore the batch dimension is 1, but one can use the same module to process more images at the same time.
149
+
150
+ The input and output values of the images should be in the range [0, 1].
151
+
152
+ The shapes of content and style image don't have to match. Output image shape
153
+ is the same as the content image shape.
154
+
155
+ ## Demonstrate image stylization
156
+ """
157
+
158
+ # Stylize content image with given style image.
159
+ # This is pretty fast within a few milliseconds on a GPU.
160
+
161
+ outputs = hub_module(tf.constant(content_image), tf.constant(style_image))
162
+ stylized_image = outputs[0]
163
+
164
+ # Visualize input images and the generated stylized image.
165
+
166
+ show_n([content_image, style_image, stylized_image], titles=['Original content image', 'Style image', 'Stylized image'])
167
+
168
+ """## Let's try it on more images"""
169
+
170
+ # @title To Run: Load more images { display-mode: "form" }
171
+
172
+ content_urls = dict(
173
+ sea_turtle='https://upload.wikimedia.org/wikipedia/commons/d/d7/Green_Sea_Turtle_grazing_seagrass.jpg',
174
+ tuebingen='https://upload.wikimedia.org/wikipedia/commons/0/00/Tuebingen_Neckarfront.jpg',
175
+ grace_hopper='https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg',
176
+ )
177
+ style_urls = dict(
178
+ kanagawa_great_wave='https://upload.wikimedia.org/wikipedia/commons/0/0a/The_Great_Wave_off_Kanagawa.jpg',
179
+ kandinsky_composition_7='https://upload.wikimedia.org/wikipedia/commons/b/b4/Vassily_Kandinsky%2C_1913_-_Composition_7.jpg',
180
+ hubble_pillars_of_creation='https://upload.wikimedia.org/wikipedia/commons/6/68/Pillars_of_creation_2014_HST_WFC3-UVIS_full-res_denoised.jpg',
181
+ van_gogh_starry_night='https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg/1024px-Van_Gogh_-_Starry_Night_-_Google_Art_Project.jpg',
182
+ turner_nantes='https://upload.wikimedia.org/wikipedia/commons/b/b7/JMW_Turner_-_Nantes_from_the_Ile_Feydeau.jpg',
183
+ munch_scream='https://upload.wikimedia.org/wikipedia/commons/c/c5/Edvard_Munch%2C_1893%2C_The_Scream%2C_oil%2C_tempera_and_pastel_on_cardboard%2C_91_x_73_cm%2C_National_Gallery_of_Norway.jpg',
184
+ picasso_demoiselles_avignon='https://upload.wikimedia.org/wikipedia/en/4/4c/Les_Demoiselles_d%27Avignon.jpg',
185
+ picasso_violin='https://upload.wikimedia.org/wikipedia/en/3/3c/Pablo_Picasso%2C_1911-12%2C_Violon_%28Violin%29%2C_oil_on_canvas%2C_Kr%C3%B6ller-M%C3%BCller_Museum%2C_Otterlo%2C_Netherlands.jpg',
186
+ picasso_bottle_of_rum='https://upload.wikimedia.org/wikipedia/en/7/7f/Pablo_Picasso%2C_1911%2C_Still_Life_with_a_Bottle_of_Rum%2C_oil_on_canvas%2C_61.3_x_50.5_cm%2C_Metropolitan_Museum_of_Art%2C_New_York.jpg',
187
+ fire='https://upload.wikimedia.org/wikipedia/commons/3/36/Large_bonfire.jpg',
188
+ derkovits_woman_head='https://upload.wikimedia.org/wikipedia/commons/0/0d/Derkovits_Gyula_Woman_head_1922.jpg',
189
+ amadeo_style_life='https://upload.wikimedia.org/wikipedia/commons/8/8e/Untitled_%28Still_life%29_%281913%29_-_Amadeo_Souza-Cardoso_%281887-1918%29_%2817385824283%29.jpg',
190
+ derkovtis_talig='https://upload.wikimedia.org/wikipedia/commons/3/37/Derkovits_Gyula_Talig%C3%A1s_1920.jpg',
191
+ amadeo_cardoso='https://upload.wikimedia.org/wikipedia/commons/7/7d/Amadeo_de_Souza-Cardoso%2C_1915_-_Landscape_with_black_figure.jpg'
192
+ )
193
+
194
+ content_image_size = 384
195
+ style_image_size = 256
196
+ content_images = {k: load_image(v, (content_image_size, content_image_size)) for k, v in content_urls.items()}
197
+ style_images = {k: load_image(v, (style_image_size, style_image_size)) for k, v in style_urls.items()}
198
+ style_images = {k: tf.nn.avg_pool(style_image, ksize=[3,3], strides=[1,1], padding='SAME') for k, style_image in style_images.items()}
199
+
200
+ #@title Specify the main content image and the style you want to use. { display-mode: "form" }
201
+
202
+ content_name = 'sea_turtle' # @param ['sea_turtle', 'tuebingen', 'grace_hopper']
203
+ style_name = 'munch_scream' # @param ['kanagawa_great_wave', 'kandinsky_composition_7', 'hubble_pillars_of_creation', 'van_gogh_starry_night', 'turner_nantes', 'munch_scream', 'picasso_demoiselles_avignon', 'picasso_violin', 'picasso_bottle_of_rum', 'fire', 'derkovits_woman_head', 'amadeo_style_life', 'derkovtis_talig', 'amadeo_cardoso']
204
+
205
+ stylized_image = hub_module(tf.constant(content_images[content_name]),
206
+ tf.constant(style_images[style_name]))[0]
207
+
208
+ show_n([content_images[content_name], style_images[style_name], stylized_image],
209
+ titles=['Original content image', 'Style image', 'Stylized image'])