|
| 1 | +''' |
| 2 | +Copyright (c) 2016 by Magnus Erik Hvass Pedersen |
| 3 | +
|
| 4 | +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: |
| 5 | +
|
| 6 | +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. |
| 7 | +
|
| 8 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 9 | +''' |
| 10 | + |
| 11 | +# https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/14_DeepDream.ipynb |
| 12 | + |
| 13 | +import matplotlib.pyplot as plt |
| 14 | +import tensorflow as tf |
| 15 | +import numpy as np |
| 16 | +import random |
| 17 | +import math |
| 18 | +# Image manipulation. |
| 19 | +import PIL.Image |
| 20 | +from scipy.ndimage.filters import gaussian_filter |
| 21 | +import inception5h |
| 22 | + |
| 23 | + |
| 24 | +model = inception5h.Inception5h() |
| 25 | +gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5) |
| 26 | +session = tf.Session(graph=model.graph, |
| 27 | + config=tf.ConfigProto(gpu_options=gpu_options)) |
| 28 | + |
| 29 | + |
| 30 | +def load_image(filename): |
| 31 | + image = PIL.Image.open(filename) |
| 32 | + return np.float32(image) |
| 33 | + |
| 34 | + |
| 35 | +def save_image(image, filename): |
| 36 | + # Ensure the pixel-values are between 0 and 255. |
| 37 | + image = np.clip(image, 0.0, 255.0) |
| 38 | + # Convert to bytes. |
| 39 | + image = image.astype(np.uint8) |
| 40 | + # Write the image-file in jpeg-format. |
| 41 | + with open(filename, 'wb') as file: |
| 42 | + PIL.Image.fromarray(image).save(file, 'jpeg') |
| 43 | + |
| 44 | + |
| 45 | +def plot_image(image): |
| 46 | + # Assume the pixel-values are scaled between 0 and 255. |
| 47 | + if False: |
| 48 | + # Convert the pixel-values to the range between 0.0 and 1.0 |
| 49 | + image = np.clip(image/255.0, 0.0, 1.0) |
| 50 | + # Plot using matplotlib. |
| 51 | + plt.imshow(image, interpolation='lanczos') |
| 52 | + plt.show() |
| 53 | + else: |
| 54 | + # Ensure the pixel-values are between 0 and 255. |
| 55 | + image = np.clip(image, 0.0, 255.0) |
| 56 | + # Convert pixels to bytes. |
| 57 | + image = image.astype(np.uint8) |
| 58 | + |
| 59 | + # Convert to a PIL-image and display it. |
| 60 | + plt.imshow(image, interpolation='lanczos') |
| 61 | + plt.show() |
| 62 | + |
| 63 | + |
| 64 | +def normalize_image(x): |
| 65 | + # Get the min and max values for all pixels in the input. |
| 66 | + x_min = x.min() |
| 67 | + x_max = x.max() |
| 68 | + |
| 69 | + # Normalize so all values are between 0.0 and 1.0 |
| 70 | + x_norm = (x - x_min) / (x_max - x_min) |
| 71 | + return x_norm |
| 72 | + |
| 73 | + |
| 74 | +def plot_gradient(gradient): |
| 75 | + # Normalize the gradient so it is between 0.0 and 1.0 |
| 76 | + gradient_normalized = normalize_image(gradient) |
| 77 | + # Plot the normalized gradient. |
| 78 | + plt.imshow(gradient_normalized, interpolation='bilinear') |
| 79 | + plt.show() |
| 80 | + |
| 81 | + |
| 82 | +def resize_image(image, size=None, factor=None): |
| 83 | + # If a rescaling-factor is provided then use it. |
| 84 | + if factor is not None: |
| 85 | + # Scale the numpy array's shape for height and width. |
| 86 | + size = np.array(image.shape[0:2]) * factor |
| 87 | + # The size is floating-point because it was scaled. |
| 88 | + # PIL requires the size to be integers. |
| 89 | + size = size.astype(int) |
| 90 | + else: |
| 91 | + # Ensure the size has length 2. |
| 92 | + size = size[0:2] |
| 93 | + # The height and width is reversed in numpy vs. PIL. |
| 94 | + size = tuple(reversed(size)) |
| 95 | + |
| 96 | + # Ensure the pixel-values are between 0 and 255. |
| 97 | + img = np.clip(image, 0.0, 255.0) |
| 98 | + # Convert the pixels to 8-bit bytes. |
| 99 | + img = img.astype(np.uint8) |
| 100 | + # Create PIL-object from numpy array. |
| 101 | + img = PIL.Image.fromarray(img) |
| 102 | + # Resize the image. |
| 103 | + img_resized = img.resize(size, PIL.Image.LANCZOS) |
| 104 | + # Convert 8-bit pixel values back to floating-point. |
| 105 | + img_resized = np.float32(img_resized) |
| 106 | + |
| 107 | + return img_resized |
| 108 | + |
| 109 | + |
| 110 | +def get_tile_size(num_pixels, tile_size=400): |
| 111 | + """ |
| 112 | + num_pixels is the number of pixels in a dimension of the image. |
| 113 | + tile_size is the desired tile-size. |
| 114 | + """ |
| 115 | + |
| 116 | + # How many times can we repeat a tile of the desired size. |
| 117 | + num_tiles = int(round(num_pixels / tile_size)) |
| 118 | + # Ensure that there is at least 1 tile. |
| 119 | + num_tiles = max(1, num_tiles) |
| 120 | + # The actual tile-size. |
| 121 | + actual_tile_size = math.ceil(num_pixels / num_tiles) |
| 122 | + return actual_tile_size |
| 123 | + |
| 124 | + |
| 125 | +def tiled_gradient(gradient, image, tile_size=400): |
| 126 | + # Allocate an array for the gradient of the entire image. |
| 127 | + grad = np.zeros_like(image) |
| 128 | + |
| 129 | + # Number of pixels for the x- and y-axes. |
| 130 | + x_max, y_max, _ = image.shape |
| 131 | + |
| 132 | + # Tile-size for the x-axis. |
| 133 | + x_tile_size = get_tile_size(num_pixels=x_max, tile_size=tile_size) |
| 134 | + # 1/4 of the tile-size. |
| 135 | + x_tile_size4 = x_tile_size // 4 |
| 136 | + |
| 137 | + # Tile-size for the y-axis. |
| 138 | + y_tile_size = get_tile_size(num_pixels=y_max, tile_size=tile_size) |
| 139 | + # 1/4 of the tile-size |
| 140 | + y_tile_size4 = y_tile_size // 4 |
| 141 | + |
| 142 | + # Random start-position for the tiles on the x-axis. |
| 143 | + # The random value is between -3/4 and -1/4 of the tile-size. |
| 144 | + # This is so the border-tiles are at least 1/4 of the tile-size, |
| 145 | + # otherwise the tiles may be too small which creates noisy gradients. |
| 146 | + x_start = random.randint(-3*x_tile_size4, -x_tile_size4) |
| 147 | + |
| 148 | + while x_start < x_max: |
| 149 | + # End-position for the current tile. |
| 150 | + x_end = x_start + x_tile_size |
| 151 | + # Ensure the tile's start- and end-positions are valid. |
| 152 | + x_start_lim = max(x_start, 0) |
| 153 | + x_end_lim = min(x_end, x_max) |
| 154 | + |
| 155 | + # Random start-position for the tiles on the y-axis. |
| 156 | + # The random value is between -3/4 and -1/4 of the tile-size. |
| 157 | + y_start = random.randint(-3*y_tile_size4, -y_tile_size4) |
| 158 | + |
| 159 | + while y_start < y_max: |
| 160 | + # End-position for the current tile. |
| 161 | + y_end = y_start + y_tile_size |
| 162 | + |
| 163 | + # Ensure the tile's start- and end-positions are valid. |
| 164 | + y_start_lim = max(y_start, 0) |
| 165 | + y_end_lim = min(y_end, y_max) |
| 166 | + |
| 167 | + # Get the image-tile. |
| 168 | + img_tile = image[x_start_lim:x_end_lim, |
| 169 | + y_start_lim:y_end_lim, :] |
| 170 | + |
| 171 | + # Create a feed-dict with the image-tile. |
| 172 | + feed_dict = model.create_feed_dict(image=img_tile) |
| 173 | + |
| 174 | + # Use TensorFlow to calculate the gradient-value. |
| 175 | + g = session.run(gradient, feed_dict=feed_dict) |
| 176 | + |
| 177 | + # Normalize the gradient for the tile. This is |
| 178 | + # necessary because the tiles may have very different |
| 179 | + # values. Normalizing gives a more coherent gradient. |
| 180 | + g /= (np.std(g) + 1e-8) |
| 181 | + |
| 182 | + # Store the tile's gradient at the appropriate location. |
| 183 | + grad[x_start_lim:x_end_lim, |
| 184 | + y_start_lim:y_end_lim, :] = g |
| 185 | + # Advance the start-position for the y-axis. |
| 186 | + y_start = y_end |
| 187 | + |
| 188 | + # Advance the start-position for the x-axis. |
| 189 | + x_start = x_end |
| 190 | + |
| 191 | + return grad |
| 192 | + |
| 193 | + |
| 194 | +def optimize_image(layer_tensor, image, |
| 195 | + num_iterations=10, step_size=3.0, tile_size=400, |
| 196 | + show_gradient=False): |
| 197 | + """ |
| 198 | + Use gradient ascent to optimize an image so it maximizes the |
| 199 | + mean value of the given layer_tensor. |
| 200 | +
|
| 201 | + Parameters: |
| 202 | + layer_tensor: Reference to a tensor that will be maximized. |
| 203 | + image: Input image used as the starting point. |
| 204 | + num_iterations: Number of optimization iterations to perform. |
| 205 | + step_size: Scale for each step of the gradient ascent. |
| 206 | + tile_size: Size of the tiles when calculating the gradient. |
| 207 | + show_gradient: Plot the gradient in each iteration. |
| 208 | + """ |
| 209 | + |
| 210 | + # Copy the image so we don't overwrite the original image. |
| 211 | + img = image.copy() |
| 212 | + |
| 213 | + print("Processing image: ") |
| 214 | + |
| 215 | + # Use TensorFlow to get the mathematical function for the |
| 216 | + # gradient of the given layer-tensor with regard to the |
| 217 | + # input image. This may cause TensorFlow to add the same |
| 218 | + # math-expressions to the graph each time this function is called. |
| 219 | + # It may use a lot of RAM and could be moved outside the function. |
| 220 | + gradient = model.get_gradient(layer_tensor) |
| 221 | + |
| 222 | + for i in range(num_iterations): |
| 223 | + # Calculate the value of the gradient. |
| 224 | + # This tells us how to change the image so as to |
| 225 | + # maximize the mean of the given layer-tensor. |
| 226 | + grad = tiled_gradient(gradient=gradient, image=img) |
| 227 | + |
| 228 | + # Blur the gradient with different amounts and add |
| 229 | + # them together. The blur amount is also increased |
| 230 | + # during the optimization. This was found to give |
| 231 | + # nice, smooth images. You can try and change the formulas. |
| 232 | + # The blur-amount is called sigma (0=no blur, 1=low blur, etc.) |
| 233 | + # We could call gaussian_filter(grad, sigma=(sigma, sigma, 0.0)) |
| 234 | + # which would not blur the colour-channel. This tends to |
| 235 | + # give psychadelic / pastel colours in the resulting images. |
| 236 | + # When the colour-channel is also blurred the colours of the |
| 237 | + # input image are mostly retained in the output image. |
| 238 | + sigma = (i * 4.0) / num_iterations + 0.5 |
| 239 | + grad_smooth1 = gaussian_filter(grad, sigma=sigma) |
| 240 | + grad_smooth2 = gaussian_filter(grad, sigma=sigma*2) |
| 241 | + grad_smooth3 = gaussian_filter(grad, sigma=sigma*0.5) |
| 242 | + grad = (grad_smooth1 + grad_smooth2 + grad_smooth3) |
| 243 | + |
| 244 | + # Scale the step-size according to the gradient-values. |
| 245 | + # This may not be necessary because the tiled-gradient |
| 246 | + # is already normalized. |
| 247 | + step_size_scaled = step_size / (np.std(grad) + 1e-8) |
| 248 | + |
| 249 | + # Update the image by following the gradient. |
| 250 | + img += grad * step_size_scaled |
| 251 | + |
| 252 | + if show_gradient: |
| 253 | + # Print statistics for the gradient. |
| 254 | + msg = "Gradient min: {0:>9.6f}, max: {1:>9.6f}, stepsize: {2:>9.2f}" |
| 255 | + print(msg.format(grad.min(), grad.max(), step_size_scaled)) |
| 256 | + |
| 257 | + # Plot the gradient. |
| 258 | + plot_gradient(grad) |
| 259 | + else: |
| 260 | + # Otherwise show a little progress-indicator. |
| 261 | + print(". ", end="") |
| 262 | + return img |
| 263 | + |
| 264 | + |
| 265 | +def recursive_optimize(layer_tensor, image, |
| 266 | + num_repeats=4, rescale_factor=0.7, blend=0.2, |
| 267 | + num_iterations=10, step_size=3.0, |
| 268 | + tile_size=400): |
| 269 | + """ |
| 270 | + Recursively blur and downscale the input image. |
| 271 | + Each downscaled image is run through the optimize_image() |
| 272 | + function to amplify the patterns that the Inception model sees. |
| 273 | +
|
| 274 | + Parameters: |
| 275 | + image: Input image used as the starting point. |
| 276 | + rescale_factor: Downscaling factor for the image. |
| 277 | + num_repeats: Number of times to downscale the image. |
| 278 | + blend: Factor for blending the original and processed images. |
| 279 | +
|
| 280 | + Parameters passed to optimize_image(): |
| 281 | + layer_tensor: Reference to a tensor that will be maximized. |
| 282 | + num_iterations: Number of optimization iterations to perform. |
| 283 | + step_size: Scale for each step of the gradient ascent. |
| 284 | + tile_size: Size of the tiles when calculating the gradient. |
| 285 | + """ |
| 286 | + |
| 287 | + # Do a recursive step? |
| 288 | + if num_repeats > 0: |
| 289 | + # Blur the input image to prevent artifacts when downscaling. |
| 290 | + # The blur amount is controlled by sigma. Note that the |
| 291 | + # colour-channel is not blurred as it would make the image gray. |
| 292 | + sigma = 0.5 |
| 293 | + img_blur = gaussian_filter(image, sigma=(sigma, sigma, 0.0)) |
| 294 | + |
| 295 | + # Downscale the image. |
| 296 | + img_downscaled = resize_image(image=img_blur, |
| 297 | + factor=rescale_factor) |
| 298 | + |
| 299 | + # Recursive call to this function. |
| 300 | + # Subtract one from num_repeats and use the downscaled image. |
| 301 | + img_result = recursive_optimize(layer_tensor=layer_tensor, |
| 302 | + image=img_downscaled, |
| 303 | + num_repeats=num_repeats-1, |
| 304 | + rescale_factor=rescale_factor, |
| 305 | + blend=blend, |
| 306 | + num_iterations=num_iterations, |
| 307 | + step_size=step_size, |
| 308 | + tile_size=tile_size) |
| 309 | + |
| 310 | + # Upscale the resulting image back to its original size. |
| 311 | + img_upscaled = resize_image(image=img_result, size=image.shape) |
| 312 | + |
| 313 | + # Blend the original and processed images. |
| 314 | + image = blend * image + (1.0 - blend) * img_upscaled |
| 315 | + |
| 316 | + print("Recursive level:", num_repeats) |
| 317 | + |
| 318 | + # Process the image using the DeepDream algorithm. |
| 319 | + img_result = optimize_image(layer_tensor=layer_tensor, |
| 320 | + image=image, |
| 321 | + num_iterations=num_iterations, |
| 322 | + step_size=step_size, |
| 323 | + tile_size=tile_size) |
| 324 | + |
| 325 | + return img_result |
0 commit comments