jeysshon commited on
Commit
e48dd40
·
verified ·
1 Parent(s): 86d32c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -47
app.py CHANGED
@@ -3,68 +3,111 @@ import numpy as np
3
  import cv2
4
  from keras.models import load_model
5
 
6
- # Load the trained models
 
 
 
7
  model1 = load_model('./isatron_v3.h5')
8
- # model2 = load_model('./Isatron_v2.h5')
9
 
10
- # Print the loaded models
11
- print(model1)
12
- # print(model2)
 
 
 
 
 
 
 
13
 
14
- # Define image size and labels
15
  img_size1 = 150
16
- # img_size2 = 224
17
  labels = ['PNEUMONIA', 'NORMAL']
18
 
19
  def load_and_preprocess_image1(img):
20
- # Convert Gradio image (PIL Image) to numpy array
21
  img = np.array(img)
22
- # Convert RGB to grayscale
23
  img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
24
- # Resize image to the required input size
25
  img = cv2.resize(img, (img_size1, img_size1))
26
- # Reshape image for model input
27
  img = img.reshape(-1, img_size1, img_size1, 1)
28
- # Normalize image
29
  img = img / 255.0
30
  return img
31
 
32
- # def load_and_preprocess_image2(img):
33
- # # Convert Gradio image (PIL Image) to numpy array
34
- # img = np.array(img)
35
- # # Convert RGB to grayscale
36
- # img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
37
- # # Resize image to the required input size
38
- # img = cv2.resize(img, (img_size2, img_size2))
39
- # # Reshape image for model input
40
- # img = img.reshape(-1, img_size2, img_size2, 1)
41
- # # Normalize image
42
- # img = img / 255.0
43
- # return img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  def image_classifier1(img):
46
- # Preprocess the image
47
- img = load_and_preprocess_image1(img)
48
- # Perform prediction using model1
49
- prediction = model1.predict(img)[0][0] # Assuming your model outputs a single probability
50
- # Return the prediction
51
- return {'PNEUMONIA': prediction, 'NORMAL': 1-prediction} # Invert the prediction for Gradio
52
-
53
- # def image_classifier2(img):
54
- # # Preprocess the image
55
- # img = load_and_preprocess_image2(img)
56
- # # Perform prediction using model2
57
- # prediction = model2.predict(img)[0][0] # Assuming your model outputs a single probability
58
- # # Return the prediction
59
- # return {'PNEUMONIA': 1-prediction, 'NORMAL': prediction} # Invert the prediction for Gradio
60
-
61
- # Create Gradio interfaces for each model
62
- demo_model1 = gr.Interface(fn=image_classifier1, inputs="image", outputs="label", title="IsaTron V2")
63
- # demo_model2 = gr.Interface(fn=image_classifier2, inputs="image", outputs="label", title="Pneumonia Detection - Model 2")
64
-
65
- # gr.Parallel(demo_model1, demo_model2).launch(share=True)
66
- # Launch the interfaces simultaneously
 
 
 
 
 
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)