fetal-unet / app.py
Turyahabwa Mark
Feat(Outputs): Add Hc Measurement Output
ed5a580
import gradio as gr
def greet(name):
return "Hello " + name
title = "A Machine Learning Strategy for Automatic Phenotyping of High Risk Pregnancies"
description = """
The bot was trained to segment, measure and make informed prediction of high risk pregnancy based off of what fetal skull Head circumference (HC) can imply!
"""
# <img src="https://huggingface.co/spaces/course-demos/Rick_and_Morty_QA/resolve/main/rick.png" width=200px>
article = "Check out [the github repository](https://github.com/MarkTLite) that this website and model are based off of."
import cv2, math
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.utils import normalize
from tensorflow.keras.models import load_model
from skimage import measure
def predict(input_img):
input_img = input_img.reshape((256,256,1))
test_normalized_image = normalize(input_img, axis=1)
# load model
model = load_model('model-best.h5',compile=False)
model.compile(optimizer='adam', loss = "binary_crossentropy")
test_img = test_normalized_image
orig_img = input_img
test_img_norm=test_img[:,:,0]
test_img_input=np.expand_dims(test_img_norm, 0)
# Predict and threshold for values above 0.08 probability
prediction = (model.predict(test_img_input) > 0.08).astype(np.uint8)
prediction = prediction[0]
label_image = measure.label(prediction, connectivity=orig_img.ndim)
fig, ax = plt.subplots()
ax.imshow(label_image[:,:,0], cmap=plt.cm.gray)
regions = measure.regionprops(label_image[:,:,0])
prev_hc, hc = 0,0
for props in regions:
y0, x0 = props.centroid
orientation = props.orientation
x1 = x0 + math.cos(orientation) * 0.5 * props.minor_axis_length
y1 = y0 - math.sin(orientation) * 0.5 * props.minor_axis_length
x2 = x0 - math.sin(orientation) * 0.5 * props.major_axis_length
y2 = y0 - math.cos(orientation) * 0.5 * props.major_axis_length
minor_distance = ((x0 - x1)**2 + (y0 - y1)**2)**0.5
print(minor_distance*2)
major_distance = ((x0 - x2)**2 + (y0 - y2)**2)**0.5
print(major_distance*2)
prev_hc = 1.62*(minor_distance+major_distance)
if(prev_hc>hc):
hc = prev_hc
print("HC = ",hc, " mm")
ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
ax.plot((x0, x2), (y0, y2), '-r', linewidth=2.5)
ax.plot(x0, y0, '.g', markersize=15)
plt.show()
# Overlap prediction on original image
drawn_img = cv2.cvtColor(orig_img, cv2.COLOR_GRAY2BGR)
contours, hierarchy = cv2.findContours(prediction,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cv2.drawContours(drawn_img, contours, -1, (255,0,0), 2)
return drawn_img, "Head Circumference = " + str(hc) + " mm"
examples = [
['image.png']
]
gr.Interface(predict,gr.Image(shape=(256, 256), image_mode='L'), [gr.outputs.Image(type='plot'),'text'],
description=description, article=article, title=title, examples=examples, analytics_enabled=False).launch()