Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,68 +3,111 @@ import numpy as np
|
|
3 |
import cv2
|
4 |
from keras.models import load_model
|
5 |
|
6 |
-
|
|
|
|
|
|
|
7 |
model1 = load_model('./isatron_v3.h5')
|
8 |
-
# model2 = load_model('./Isatron_v2.h5')
|
9 |
|
10 |
-
#
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
#
|
15 |
img_size1 = 150
|
16 |
-
# img_size2 = 224
|
17 |
labels = ['PNEUMONIA', 'NORMAL']
|
18 |
|
19 |
def load_and_preprocess_image1(img):
|
20 |
-
#
|
21 |
img = np.array(img)
|
22 |
-
#
|
23 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
24 |
-
#
|
25 |
img = cv2.resize(img, (img_size1, img_size1))
|
26 |
-
#
|
27 |
img = img.reshape(-1, img_size1, img_size1, 1)
|
28 |
-
#
|
29 |
img = img / 255.0
|
30 |
return img
|
31 |
|
32 |
-
|
33 |
-
#
|
34 |
-
#
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
#
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
def image_classifier1(img):
|
46 |
-
#
|
47 |
-
|
48 |
-
#
|
49 |
-
|
50 |
-
#
|
51 |
-
|
52 |
-
|
53 |
-
#
|
54 |
-
|
55 |
-
#
|
56 |
-
|
57 |
-
#
|
58 |
-
|
59 |
-
#
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
#
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
67 |
if __name__ == "__main__":
|
68 |
-
# demo_model1.launch(share=True)
|
69 |
demo_model1.launch(share=True)
|
70 |
-
|
|
|
3 |
import cv2
|
4 |
from keras.models import load_model
|
5 |
|
6 |
+
import tensorflow as tf
|
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):
|
14 |
+
for layer in reversed(model.layers):
|
15 |
+
if 'conv' in layer.name:
|
16 |
+
return layer.name
|
17 |
+
raise ValueError("No se encontró una capa convolucional en el modelo.")
|
18 |
+
|
19 |
+
# Obtener el nombre de la última capa convolucional
|
20 |
+
last_conv_layer_name = find_last_conv_layer(model1)
|
21 |
+
print("Última capa convolucional:", last_conv_layer_name)
|
22 |
|
23 |
+
# Definir tamaño de imagen y etiquetas
|
24 |
img_size1 = 150
|
|
|
25 |
labels = ['PNEUMONIA', 'NORMAL']
|
26 |
|
27 |
def load_and_preprocess_image1(img):
|
28 |
+
# Convertir imagen de Gradio (PIL Image) a array numpy
|
29 |
img = np.array(img)
|
30 |
+
# Convertir de RGB a escala de grises
|
31 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
|
32 |
+
# Redimensionar imagen al tamaño requerido
|
33 |
img = cv2.resize(img, (img_size1, img_size1))
|
34 |
+
# Reformatear imagen para entrada del modelo
|
35 |
img = img.reshape(-1, img_size1, img_size1, 1)
|
36 |
+
# Normalizar imagen
|
37 |
img = img / 255.0
|
38 |
return img
|
39 |
|
40 |
+
def make_gradcam_heatmap(img_array, model, last_conv_layer_name, pred_index=None):
|
41 |
+
# Crear un modelo que mapee la imagen de entrada a las activaciones
|
42 |
+
# de la última capa convolucional y las predicciones
|
43 |
+
grad_model = keras.models.Model(
|
44 |
+
[model.inputs], [model.get_layer(last_conv_layer_name).output, model.output]
|
45 |
+
)
|
46 |
+
|
47 |
+
# Calcular el gradiente de la clase predicha con respecto a las activaciones
|
48 |
+
with tf.GradientTape() as tape:
|
49 |
+
last_conv_layer_output, preds = grad_model(img_array)
|
50 |
+
if pred_index is None:
|
51 |
+
pred_index = np.argmax(preds[0])
|
52 |
+
class_channel = preds[:, pred_index]
|
53 |
+
|
54 |
+
# Calcular los gradientes
|
55 |
+
grads = tape.gradient(class_channel, last_conv_layer_output)
|
56 |
+
|
57 |
+
# Pooling global de los gradientes
|
58 |
+
pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))
|
59 |
+
|
60 |
+
# Multiplicar cada canal por su importancia
|
61 |
+
last_conv_layer_output = last_conv_layer_output[0]
|
62 |
+
heatmap = last_conv_layer_output @ pooled_grads[..., tf.newaxis]
|
63 |
+
heatmap = tf.squeeze(heatmap)
|
64 |
+
|
65 |
+
# Normalizar el mapa de calor entre 0 y 1
|
66 |
+
heatmap = tf.maximum(heatmap, 0) / tf.reduce_max(heatmap)
|
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):
|
86 |
+
# Mantener la imagen original para superponer
|
87 |
+
orig_img = np.array(img)
|
88 |
+
# Preprocesar la imagen
|
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
|
112 |
if __name__ == "__main__":
|
|
|
113 |
demo_model1.launch(share=True)
|
|