Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,28 +3,50 @@ import tensorflow as tf
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
-
# Load
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
style = Image.fromarray(style).resize((256, 256))
|
| 12 |
-
|
| 13 |
-
# preprocess (example: normalize, expand dims, etc.)
|
| 14 |
-
content_arr = np.expand_dims(np.array(content) / 255.0, axis=0)
|
| 15 |
-
style_arr = np.expand_dims(np.array(style) / 255.0, axis=0)
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
demo = gr.Interface(
|
| 25 |
fn=style_transfer,
|
| 26 |
-
inputs=[gr.Image(type="numpy"
|
| 27 |
-
|
|
|
|
| 28 |
)
|
| 29 |
|
| 30 |
demo.launch()
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
from PIL import Image
|
| 5 |
|
| 6 |
+
# Load VGG for feature extraction
|
| 7 |
+
vgg = tf.keras.applications.VGG19(include_top=False, weights="imagenet")
|
| 8 |
+
vgg.trainable = False
|
| 9 |
|
| 10 |
+
STYLE_LAYERS = [...] # same layers as in your notebook
|
| 11 |
+
CONTENT_LAYER = [...] # e.g. [('block5_conv4', 1)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
def preprocess(img):
|
| 14 |
+
img = Image.fromarray(img).resize((256, 256))
|
| 15 |
+
arr = np.expand_dims(np.array(img) / 255.0, axis=0).astype(np.float32)
|
| 16 |
+
return tf.convert_to_tensor(arr)
|
| 17 |
|
| 18 |
+
def style_transfer(content, style, steps=50):
|
| 19 |
+
content_tensor = preprocess(content)
|
| 20 |
+
style_tensor = preprocess(style)
|
| 21 |
+
|
| 22 |
+
# Extract features
|
| 23 |
+
a_C = vgg(content_tensor)
|
| 24 |
+
a_S = vgg(style_tensor)
|
| 25 |
+
|
| 26 |
+
# Init generated image
|
| 27 |
+
generated_image = tf.Variable(content_tensor)
|
| 28 |
+
|
| 29 |
+
# Optimize
|
| 30 |
+
opt = tf.keras.optimizers.Adam(learning_rate=0.01)
|
| 31 |
+
for i in range(steps):
|
| 32 |
+
with tf.GradientTape() as tape:
|
| 33 |
+
a_G = vgg(generated_image)
|
| 34 |
+
J_style = compute_style_cost(a_S, a_G)
|
| 35 |
+
J_content = compute_content_cost(a_C, a_G)
|
| 36 |
+
J = total_cost(J_content, J_style, alpha=10, beta=40)
|
| 37 |
+
|
| 38 |
+
grad = tape.gradient(J, generated_image)
|
| 39 |
+
opt.apply_gradients([(grad, generated_image)])
|
| 40 |
+
generated_image.assign(tf.clip_by_value(generated_image, 0.0, 1.0))
|
| 41 |
+
|
| 42 |
+
out_img = (generated_image[0].numpy() * 255).astype("uint8")
|
| 43 |
+
return Image.fromarray(out_img)
|
| 44 |
|
| 45 |
demo = gr.Interface(
|
| 46 |
fn=style_transfer,
|
| 47 |
+
inputs=[gr.Image(type="numpy", label="Content Image"),
|
| 48 |
+
gr.Image(type="numpy", label="Style Image")],
|
| 49 |
+
outputs=gr.Image(type="pil", label="Stylized Image"),
|
| 50 |
)
|
| 51 |
|
| 52 |
demo.launch()
|