Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import cv2
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# Suppress TensorFlow logging
|
| 8 |
+
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
|
| 9 |
+
|
| 10 |
+
# Constants
|
| 11 |
+
IMAGE_H = 512
|
| 12 |
+
IMAGE_W = 512
|
| 13 |
+
NUM_CLASSES = 11
|
| 14 |
+
|
| 15 |
+
# RGB color codes for each class
|
| 16 |
+
RGB_CODES = [
|
| 17 |
+
[0, 0, 0], [0, 153, 255], [102, 255, 153], [0, 204, 153],
|
| 18 |
+
[255, 255, 102], [255, 255, 204], [255, 153, 0], [255, 102, 255],
|
| 19 |
+
[102, 0, 51], [255, 204, 255], [255, 0, 102]
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
# Load the trained model
|
| 23 |
+
model = tf.keras.models.load_model("ten_epoch_model.h5")
|
| 24 |
+
|
| 25 |
+
# Function to convert grayscale mask to RGB mask
|
| 26 |
+
def grayscale_to_rgb(mask, rgb_codes):
|
| 27 |
+
h, w = mask.shape[0], mask.shape[1]
|
| 28 |
+
mask = mask.astype(np.int32)
|
| 29 |
+
output = [rgb_codes[pixel] for pixel in mask.flatten()]
|
| 30 |
+
return np.reshape(output, (h, w, 3)).astype(np.uint8)
|
| 31 |
+
|
| 32 |
+
# Gradio inference function
|
| 33 |
+
def segment_face(image):
|
| 34 |
+
# Resize and normalize input image
|
| 35 |
+
image_resized = cv2.resize(image, (IMAGE_W, IMAGE_H))
|
| 36 |
+
image_input = image_resized / 255.0
|
| 37 |
+
image_input = np.expand_dims(image_input, axis=0).astype(np.float32)
|
| 38 |
+
|
| 39 |
+
# Predict the mask
|
| 40 |
+
pred = model.predict(image_input, verbose=0)[0]
|
| 41 |
+
pred_mask = np.argmax(pred, axis=-1).astype(np.uint8)
|
| 42 |
+
|
| 43 |
+
# Convert predicted mask to RGB
|
| 44 |
+
rgb_mask = grayscale_to_rgb(pred_mask, RGB_CODES)
|
| 45 |
+
|
| 46 |
+
return rgb_mask
|
| 47 |
+
|
| 48 |
+
# Launch Gradio app
|
| 49 |
+
iface = gr.Interface(
|
| 50 |
+
fn=segment_face,
|
| 51 |
+
inputs=gr.Image(type="numpy", label="Upload Face Image"),
|
| 52 |
+
outputs=gr.Image(type="numpy", label="Segmentation Mask"),
|
| 53 |
+
title="Face Segmentation using Deep Learning",
|
| 54 |
+
description="Upload a face image to get a segmentation mask with different facial components marked in color."
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if __name__ == "__main__":
|
| 58 |
+
iface.launch()
|