jeysshon commited on
Commit
abea708
·
verified ·
1 Parent(s): a93df6f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -39
app.py CHANGED
@@ -7,7 +7,7 @@ import tensorflow as tf
7
  from tensorflow import keras
8
 
9
  # Cargar el modelo entrenado
10
- model1 = load_model('./isatron_v3.h5') # Cambiado a isatron_v3.h5
11
 
12
  # Función para encontrar la última capa convolucional
13
  def find_last_conv_layer(model):
@@ -67,27 +67,19 @@ def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None
67
  heatmap = heatmap.numpy()
68
  return heatmap
69
 
70
- def overlay_heatmap(heatmap, img, alpha=0.3):
71
- # Redimensionar el mapa de calor al tamaño de la imagen
72
  heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
73
-
74
- # Aplicar un umbral al mapa de calor para resaltar solo las zonas importantes
75
- threshold = 0.6 # Solo mostrar las áreas con alta activación
76
- heatmap[heatmap < threshold] = 0
77
-
78
- # Aplicar el colormap JET para mantener los colores, pero suavizar la superposición
79
  heatmap = np.uint8(255 * heatmap)
80
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
81
-
82
- # Convertir la imagen original a BGR para poder mezclar con el mapa de calor
83
  img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
84
-
85
- # Superponer el mapa de calor en la imagen original
86
- overlayed_img = cv2.addWeighted(heatmap, alpha, img, 1 - alpha, 0)
87
-
88
  # Convertir de nuevo a RGB
89
  overlayed_img = cv2.cvtColor(overlayed_img, cv2.COLOR_BGR2RGB)
90
-
91
  return overlayed_img
92
 
93
  def image_classifier1(img):
@@ -97,37 +89,23 @@ def image_classifier1(img):
97
  img_array = load_and_preprocess_image1(img)
98
  # Realizar predicción usando model1
99
  preds = model1.predict(img_array)
100
-
101
- # Asumimos que el modelo devuelve una probabilidad entre 0 y 1 para PNEUMONIA
102
- prediction = preds[0][0] # Suponiendo que el modelo devuelve la probabilidad de neumonía
103
-
104
- # Si la predicción es mayor a 0.5, consideramos que es neumonía
105
- if prediction > 0.5:
106
- pred_label = "PNEUMONIA"
107
- prediction_percentage = {'PNEUMONIA': float(prediction * 100), 'NORMAL': float((1 - prediction) * 100)}
108
- else:
109
- pred_label = "NORMAL"
110
- prediction_percentage = {'NORMAL': float((1 - prediction) * 100), 'PNEUMONIA': float(prediction * 100)}
111
-
112
  # Generar mapa de calor
113
- heatmap = make_gradcam_heatmap(img_array, model1, last_conv_layer_name, pred_index=int(prediction > 0.5))
114
  # Superponer mapa de calor en la imagen original
115
  overlayed_img = overlay_heatmap(heatmap, orig_img)
116
-
117
  # Retornar la imagen superpuesta y los porcentajes de predicción
 
118
  return overlayed_img, prediction_percentage
119
 
120
- # Crear interfaz Gradio con estilo predeterminado y pie de página
121
  demo_model1 = gr.Interface(
122
  fn=image_classifier1,
123
- inputs=gr.Image(type="pil", label="Sube una imagen de radiografía"),
124
- outputs=[
125
- gr.Image(type="numpy", label="Imagen con Mapa de Calor"),
126
- gr.Label(num_top_classes=2, label="Resultados de Predicción")
127
- ],
128
- title="IsaTron V2 con Mapa de Calor",
129
- description="Esta aplicación detecta neumonía a partir de imágenes de radiografías de tórax.",
130
- article="Jeysshon 2024"
131
  )
132
 
133
  # Ejecutar la interfaz
 
7
  from tensorflow import keras
8
 
9
  # Cargar el modelo entrenado
10
+ model1 = load_model('./isatron_v3.h5')
11
 
12
  # Función para encontrar la última capa convolucional
13
  def find_last_conv_layer(model):
 
67
  heatmap = heatmap.numpy()
68
  return heatmap
69
 
70
+ def overlay_heatmap(heatmap, img, alpha=0.4):
71
+ # Redimensionar mapa de calor al tamaño de la imagen
72
  heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0]))
73
+ # Convertir mapa de calor a RGB
 
 
 
 
 
74
  heatmap = np.uint8(255 * heatmap)
75
  heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)
76
+ # Convertir imagen a BGR
 
77
  img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
78
+ # Aplicar mapa de calor a la imagen original
79
+ overlayed_img = heatmap * alpha + img
80
+ overlayed_img = np.uint8(overlayed_img)
 
81
  # Convertir de nuevo a RGB
82
  overlayed_img = cv2.cvtColor(overlayed_img, cv2.COLOR_BGR2RGB)
 
83
  return overlayed_img
84
 
85
  def image_classifier1(img):
 
89
  img_array = load_and_preprocess_image1(img)
90
  # Realizar predicción usando model1
91
  preds = model1.predict(img_array)
92
+ prediction = preds[0][0] # Suponiendo que el modelo devuelve una probabilidad
93
+ # Determinar el índice de la clase predicha
94
+ pred_index = int(prediction > 0.5)
 
 
 
 
 
 
 
 
 
95
  # Generar mapa de calor
96
+ heatmap = make_gradcam_heatmap(img_array, model1, last_conv_layer_name, pred_index=pred_index)
97
  # Superponer mapa de calor en la imagen original
98
  overlayed_img = overlay_heatmap(heatmap, orig_img)
 
99
  # Retornar la imagen superpuesta y los porcentajes de predicción
100
+ prediction_percentage = {'PNEUMONIA': float(prediction), 'NORMAL': float(1 - prediction)}
101
  return overlayed_img, prediction_percentage
102
 
103
+ # Crear interfaz Gradio
104
  demo_model1 = gr.Interface(
105
  fn=image_classifier1,
106
+ inputs="image",
107
+ outputs=[gr.outputs.Image(type="numpy"), "label"],
108
+ title="IsaTron V2 con Mapa de Calor"
 
 
 
 
 
109
  )
110
 
111
  # Ejecutar la interfaz