|
import gradio as gr |
|
import tensorflow as tf |
|
import numpy as np |
|
import cv2 |
|
from keras.utils import normalize |
|
from PIL import Image |
|
|
|
def dice_coef(y_true, y_pred): |
|
smooth = 1e-5 |
|
intersection = K.sum(y_true * y_pred, axis=[1, 2, 3]) |
|
union = K.sum(y_true, axis=[1, 2, 3]) + K.sum(y_pred, axis=[1, 2, 3]) |
|
return K.mean((2.0 * intersection + smooth) / (union + smooth), axis=0) |
|
|
|
def predict_segmentation(image): |
|
original_size = (image.shape[1], image.shape[0]) |
|
|
|
|
|
SIZE_X = 128 |
|
SIZE_Y = 128 |
|
img = cv2.resize(image, (SIZE_Y, SIZE_X)) |
|
|
|
if len(img.shape) == 3 and img.shape[2] == 3: |
|
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
|
|
|
img = np.expand_dims(img, axis=2) |
|
img = normalize(img, axis=1) |
|
X_test = np.expand_dims(img, axis=0) |
|
|
|
custom_objects = {'dice_coef': dice_coef} |
|
with tf.keras.utils.custom_object_scope(custom_objects): |
|
model = tf.keras.models.load_model("model_best.h5") |
|
|
|
|
|
prediction = model.predict(X_test) |
|
predicted_img = np.argmax(prediction, axis=3)[0, :, :] |
|
|
|
|
|
predicted_img_resized = cv2.resize(predicted_img, original_size, interpolation=cv2.INTER_NEAREST) |
|
|
|
|
|
rgba_img = np.zeros((predicted_img_resized.shape[0], predicted_img_resized.shape[1], 4), dtype=np.uint8) |
|
|
|
|
|
segmented_color = [255, 0, 0] |
|
|
|
|
|
for i in range(3): |
|
rgba_img[:, :, i] = np.where(predicted_img_resized > 0, segmented_color[i], 0) |
|
|
|
|
|
rgba_img[:, :, 3] = np.where(predicted_img_resized > 0, 255, 0) |
|
|
|
|
|
output_image = Image.fromarray(rgba_img) |
|
|
|
|
|
output_image_path = "/tmp/segmented_output.png" |
|
output_image.save(output_image_path) |
|
|
|
return output_image_path |
|
|
|
|
|
iface = gr.Interface( |
|
fn=predict_segmentation, |
|
inputs="image", |
|
outputs="file", |
|
live=False |
|
) |
|
|
|
iface.launch() |