DHEIVER commited on
Commit
06d1764
1 Parent(s): 09b486d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -46
app.py CHANGED
@@ -1,16 +1,15 @@
1
  import gradio as gr
2
 
3
 
4
- def greet(name):
5
- return "Hello " + name
6
-
7
- title = "A Machine Learning Strategy for Automatic Phenotyping of High Risk Pregnancies"
8
- description = """
9
- 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!
10
 
 
 
 
11
  """
12
  # <img src="https://huggingface.co/spaces/course-demos/Rick_and_Morty_QA/resolve/main/rick.png" width=200px>
13
- article = "Check out [the github repository](https://github.com/MarkTLite) that this website and model are based off of."
14
 
15
  import cv2, math
16
  import matplotlib.pyplot as plt
@@ -20,41 +19,41 @@ from tensorflow.keras.models import load_model
20
  from skimage import measure
21
 
22
 
23
- def predict(input_img):
24
- input_img = input_img.reshape((256,256,1))
25
- test_normalized_image = normalize(input_img, axis=1)
26
- # load model
27
- model = load_model('model-best.h5',compile=False)
28
- model.compile(optimizer='adam', loss = "binary_crossentropy")
29
- test_img = test_normalized_image
30
- orig_img = input_img
31
- test_img_norm=test_img[:,:,0]
32
- test_img_input=np.expand_dims(test_img_norm, 0)
33
 
34
- # Predict and threshold for values above 0.08 probability
35
- prediction = (model.predict(test_img_input) > 0.08).astype(np.uint8)
36
- prediction = prediction[0]
37
- label_image = measure.label(prediction, connectivity=orig_img.ndim)
38
 
39
  fig, ax = plt.subplots()
40
- ax.imshow(label_image[:,:,0], cmap=plt.cm.gray)
41
- regions = measure.regionprops(label_image[:,:,0])
42
- prev_hc, hc = 0,0
43
- for props in regions:
44
  y0, x0 = props.centroid
45
- orientation = props.orientation
46
- x1 = x0 + math.cos(orientation) * 0.5 * props.minor_axis_length
47
- y1 = y0 - math.sin(orientation) * 0.5 * props.minor_axis_length
48
- x2 = x0 - math.sin(orientation) * 0.5 * props.major_axis_length
49
- y2 = y0 - math.cos(orientation) * 0.5 * props.major_axis_length
50
 
51
- minor_distance = ((x0 - x1)**2 + (y0 - y1)**2)**0.5
52
- print(minor_distance*2)
53
- major_distance = ((x0 - x2)**2 + (y0 - y2)**2)**0.5
54
- print(major_distance*2)
55
- prev_hc = 1.62*(minor_distance+major_distance)
56
- if(prev_hc>hc):
57
- hc = prev_hc
58
  print("HC = ",hc, " mm")
59
 
60
  ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
@@ -63,15 +62,14 @@ def predict(input_img):
63
 
64
  plt.show()
65
 
66
- # Overlap prediction on original image
67
- drawn_img = cv2.cvtColor(orig_img, cv2.COLOR_GRAY2BGR)
68
- contours, hierarchy = cv2.findContours(prediction,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
69
- cv2.drawContours(drawn_img, contours, -1, (255,0,0), 2)
70
- return drawn_img, "Head Circumference = " + str(hc) + " mm"
71
 
72
- examples = [
73
- ['image.png']
74
  ]
75
 
76
- gr.Interface(predict,gr.Image(shape=(256, 256), image_mode='L'), [gr.outputs.Image(type='plot'),'text'],
77
- description=description, article=article, title=title, examples=examples, analytics_enabled=False).launch()
 
1
  import gradio as gr
2
 
3
 
4
+ def saudar(nome):
5
+ return "Olá " + nome
 
 
 
 
6
 
7
+ título = "Uma Estratégia de Aprendizado de Máquina para a Fenotipagem Automática de Gravidezes de Alto Risco"
8
+ descrição = """
9
+ O bot foi treinado para segmentar, medir e fazer previsões informadas sobre gravidezes de alto risco com base no que o perímetro cefálico (HC) do crânio fetal pode implicar!
10
  """
11
  # <img src="https://huggingface.co/spaces/course-demos/Rick_and_Morty_QA/resolve/main/rick.png" width=200px>
12
+ artigo = "Confira [o repositório do GitHub](https://github.com/MarkTLite) no qual este site e modelo são baseados."
13
 
14
  import cv2, math
15
  import matplotlib.pyplot as plt
 
19
  from skimage import measure
20
 
21
 
22
+ def prever(img):
23
+ img = img.reshape((256,256,1))
24
+ img_normalizada = normalize(img, axis=1)
25
+ # carregar o modelo
26
+ modelo = load_model('model-best.h5', compile=False)
27
+ modelo.compile(optimizer='adam', loss="binary_crossentropy")
28
+ img_teste = img_normalizada
29
+ img_original = img
30
+ img_normalizada = img_teste[:,:,0]
31
+ img_entrada = np.expand_dims(img_normalizada, 0)
32
 
33
+ # Prever e aplicar limiar para valores acima de 0.08 de probabilidade
34
+ previsão = (modelo.predict(img_entrada) > 0.08).astype(np.uint8)
35
+ previsão = previsão[0]
36
+ imagem_rótulo = measure.label(previsão, connectivity=img_original.ndim)
37
 
38
  fig, ax = plt.subplots()
39
+ ax.imshow(imagem_rótulo[:,:,0], cmap=plt.cm.gray)
40
+ regiões = measure.regionprops(imagem_rótulo[:,:,0])
41
+ hc_anterior, hc = 0,0
42
+ for props in regiões:
43
  y0, x0 = props.centroid
44
+ orientação = props.orientation
45
+ x1 = x0 + math.cos(orientação) * 0.5 * props.minor_axis_length
46
+ y1 = y0 - math.sin(orientação) * 0.5 * props.minor_axis_length
47
+ x2 = x0 - math.sin(orientação) * 0.5 * props.major_axis_length
48
+ y2 = y0 - math.cos(orientação) * 0.5 * props.major_axis_length
49
 
50
+ distância_menor = ((x0 - x1)**2 + (y0 - y1)**2)**0.5
51
+ print(distância_menor*2)
52
+ distância_maior = ((x0 - x2)**2 + (y0 - y2)**2)**0.5
53
+ print(distância_maior*2)
54
+ hc_anterior = 1.62*(distância_menor+distância_maior)
55
+ if(hc_anterior>hc):
56
+ hc = hc_anterior
57
  print("HC = ",hc, " mm")
58
 
59
  ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
 
62
 
63
  plt.show()
64
 
65
+ # Sobrepõe a previsão na imagem original
66
+ img_desenhada = cv2.cvtColor(img_original, cv2.COLOR_GRAY2BGR)
67
+ contornos, hierarquia = cv2.findContours(previsão, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
68
+ cv2.drawContours(img_desenhada, contornos, -1, (255,0,0), 2)
69
+ return img_desenhada, "Perímetro Cefálico = " + str(hc) + " mm"
70
 
71
+ exemplos = [ ['image.png']
 
72
  ]
73
 
74
+ gr.Interface(prever, gr.Image(shape=(256, 256), image_mode='L'), [gr.outputs.Image(type='plot'), 'text'],
75
+ description=descrição, article=artigo, title=título, examples=exemplos, analytics_enabled=False).launch()