Spaces:
Runtime error
Runtime error
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829302 unmodified linesimport numpy as npfrom PIL import Image# Load your Keras modelmodel = tf.keras.models.load_model("NeuralStyleTransferModel.keras")def style_transfer(content, style):content = Image.fromarray(content).resize((256, 256))style = Image.fromarray(style).resize((256, 256))# preprocess (example: normalize, expand dims, etc.)content_arr = np.expand_dims(np.array(content) / 255.0, axis=0)style_arr = np.expand_dims(np.array(style) / 255.0, axis=0)# run through your modeloutput = model.predict([content_arr, style_arr])# postprocessoutput_img = (output[0] * 255).astype("uint8")return Image.fromarray(output_img)demo = gr.Interface(fn=style_transfer,inputs=[gr.Image(type="numpy"), gr.Image(type="numpy")],outputs=gr.Image(),)demo.launch()2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051522 unmodified linesimport numpy as npfrom PIL import Image# Load VGG for feature extractionvgg = tf.keras.applications.VGG19(include_top=False, weights="imagenet")vgg.trainable = FalseSTYLE_LAYERS = [...] # same layers as in your notebookCONTENT_LAYER = [...] # e.g. [('block5_conv4', 1)]def preprocess(img):img = Image.fromarray(img).resize((256, 256))arr = np.expand_dims(np.array(img) / 255.0, axis=0).astype(np.float32)return tf.convert_to_tensor(arr)def style_transfer(content, style, steps=50):content_tensor = preprocess(content)style_tensor = preprocess(style)# Extract featuresa_C = vgg(content_tensor)a_S = vgg(style_tensor)# Init generated imagegenerated_image = tf.Variable(content_tensor)# Optimizeopt = tf.keras.optimizers.Adam(learning_rate=0.01)for i in range(steps):with tf.GradientTape() as tape:a_G = vgg(generated_image)J_style = compute_style_cost(a_S, a_G)J_content = compute_content_cost(a_C, a_G)J = total_cost(J_content, J_style, alpha=10, beta=40)grad = tape.gradient(J, generated_image)opt.apply_gradients([(grad, generated_image)])generated_image.assign(tf.clip_by_value(generated_image, 0.0, 1.0))out_img = (generated_image[0].numpy() * 255).astype("uint8")return Image.fromarray(out_img)demo = gr.Interface(fn=style_transfer,inputs=[gr.Image(type="numpy", label="Content Image"),gr.Image(type="numpy", label="Style Image")],outputs=gr.Image(type="pil", label="Stylized Image"),)demo.launch()
app.py+38-16