Spaces:
Runtime error
Runtime error
ascarlettvfx
commited on
Commit
•
50046e4
1
Parent(s):
bfd47ca
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
def load_image(image):
|
6 |
+
""" Convert uploaded image to grayscale. """
|
7 |
+
return image.convert('L')
|
8 |
+
|
9 |
+
def compute_gradients(image):
|
10 |
+
""" Compute horizontal and vertical gradients of the image. """
|
11 |
+
image_array = np.asarray(image, dtype=float)
|
12 |
+
x_gradient = np.gradient(image_array, axis=1)
|
13 |
+
y_gradient = np.gradient(image_array, axis=0)
|
14 |
+
return x_gradient, y_gradient
|
15 |
+
|
16 |
+
def create_normal_map(image):
|
17 |
+
""" Generate a normal map from an image. """
|
18 |
+
image = load_image(image)
|
19 |
+
x_grad, y_grad = compute_gradients(image)
|
20 |
+
|
21 |
+
# Normalize gradients
|
22 |
+
max_grad = max(np.max(np.abs(x_grad)), np.max(np.abs(y_grad)))
|
23 |
+
x_grad /= max_grad
|
24 |
+
y_grad /= max_grad
|
25 |
+
|
26 |
+
# Calculate z component of the normal (assumed perpendicular to the surface)
|
27 |
+
z = np.sqrt(1 - (x_grad ** 2) - (y_grad ** 2))
|
28 |
+
|
29 |
+
# Normalize to 0-255 and format as uint8
|
30 |
+
normal_map = np.dstack(((x_grad * 0.5 + 0.5) * 255,
|
31 |
+
(y_grad * 0.5 + 0.5) * 255,
|
32 |
+
(z * 1.0) * 255)).astype(np.uint8)
|
33 |
+
|
34 |
+
return Image.fromarray(normal_map, 'RGB')
|
35 |
+
|
36 |
+
def convert_to_grayscale(image):
|
37 |
+
""" Convert the normal map to a grayscale image. """
|
38 |
+
grayscale_image = image.convert('L')
|
39 |
+
return grayscale_image
|
40 |
+
|
41 |
+
def interface(image):
|
42 |
+
normal_map = create_normal_map(image)
|
43 |
+
grayscale_image = convert_to_grayscale(normal_map)
|
44 |
+
return normal_map, grayscale_image
|
45 |
+
|
46 |
+
# Set up the Gradio interface
|
47 |
+
iface = gr.Interface(
|
48 |
+
fn=interface,
|
49 |
+
inputs=gr.Image(type="pil", label="Upload Image"),
|
50 |
+
outputs=[gr.Image(type="pil", label="Normal Map"), gr.Image(type="pil", label="Grayscale Image")],
|
51 |
+
title="Normal Map and Grayscale Generator",
|
52 |
+
description="Upload an image to generate its normal map and a grayscale version of the normal map. Both images retain the original dimensions."
|
53 |
+
)
|
54 |
+
|
55 |
+
iface.launch()
|