DHEIVER commited on
Commit
da33e50
1 Parent(s): eeec150

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -85
app.py CHANGED
@@ -1,91 +1,41 @@
1
  import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
- from PIL import Image
5
  import cv2
6
  import datetime
7
- from tensorflow.keras import backend as K
8
 
9
- # Define the custom FixedDropout layer
10
- class FixedDropout(tf.keras.layers.Layer):
11
- def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
12
- super(FixedDropout, self).__init__(**kwargs)
13
- self.rate = rate
14
- self.noise_shape = noise_shape # Include the noise_shape argument
15
- self.seed = seed # Include the seed argument
16
-
17
- def call(self, inputs, training=None):
18
- if training is None:
19
- training = K.learning_phase()
20
-
21
- if training:
22
- return K.in_train_phase(K.dropout(inputs, self.rate, noise_shape=self.noise_shape, seed=self.seed), inputs, training=training)
23
- else:
24
- return inputs
25
-
26
- def get_config(self):
27
- config = super(FixedDropout, self).get_config()
28
- config['rate'] = self.rate # Serialize the rate argument
29
- config['noise_shape'] = self.noise_shape # Serialize the noise_shape argument
30
- config['seed'] = self.seed # Serialize the seed argument
31
- return config
32
-
33
- class ImageClassifierCataract:
34
- def __init__(self, model_path):
35
- self.model_path = model_path
36
- self.model = self.load_model()
37
- self.class_labels = ["Normal", "Cataract"]
38
-
39
- def load_model(self):
40
- # Load the trained TensorFlow model
41
- with tf.keras.utils.custom_object_scope({'FixedDropout': FixedDropout}):
42
- model = tf.keras.models.load_model(self.model_path)
43
- return model
44
-
45
- def classify_image(self, input_image):
46
- input_image = tf.image.resize(input_image, (192, 256))
47
- input_image = (input_image / 255.0)
48
- input_image = np.expand_dims(input_image, axis=0)
49
-
50
- current_time = datetime.datetime.now()
51
- prediction = self.model.predict(input_image)
52
- class_index = np.argmax(prediction)
53
- predicted_class = self.class_labels[class_index]
54
-
55
- # Create a formatted HTML block with the provided information in Portuguese
56
- info_html = """
57
- <div style="background-color: #f2f2f2; padding: 10px; text-align: center;">
58
- <h2>Detecção de Catarata</h2>
59
- <p>A catarata é uma das doenças oculares mais graves que pode causar cegueira se não for tratada. A detecção da doença em estágios iniciais, em vez de estágios avançados, pode evitar que o paciente fique cego.</p>
60
- <p>Neste ponto, os pacientes suspeitos devem ser constantemente examinados. O controle contínuo e o acompanhamento dos pacientes são processos cansativos e laboriosos. Por essas razões, neste artigo, são propostos dois modelos de aprendizado profundo diferentes que podem ser usados no diagnóstico e detecção de catarata para auxiliar o trabalho e os procedimentos dos oftalmologistas.</p>
61
- <p>Os modelos de aprendizado profundo propostos foram executados em um conjunto de dados de fundo de olho com sintomas normais e de catarata.</p>
62
- <h3>Resultado da Classificação:</h3>
63
- <p><strong>Predicted Class:</strong> {predicted_class}</p>
64
- </div>
65
- """
66
-
67
- # Create a copy of the input image for display
68
- output_image = input_image[0].copy()
69
- output_image = (output_image * 255).astype('uint8')
70
-
71
- # Combine the output elements
72
- output = {
73
- "image": output_image,
74
- "html": info_html,
75
- }
76
-
77
- return output
78
-
79
- def run_interface(self):
80
- input_interface = gr.Interface(
81
- fn=self.classify_image,
82
- inputs="image",
83
- outputs=["image", "html"],
84
- live=True
85
- )
86
- input_interface.launch()
87
-
88
- if __name__ == "__main__":
89
- model_path = 'modelo_treinado.h5' # Replace with the path to your trained model
90
- app = ImageClassifierCataract(model_path)
91
- app.run_interface()
 
1
  import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
 
4
  import cv2
5
  import datetime
 
6
 
7
+ # Carregue o modelo treinado
8
+ model_path = 'modelo_treinado.h5'
9
+ model = tf.keras.models.load_model(model_path)
10
+
11
+ class_labels = ["Normal", "Cataract"]
12
+
13
+ def classify_image(input_image):
14
+ # Redimensione a imagem de entrada para o tamanho esperado pelo modelo
15
+ input_image = tf.image.resize(input_image, (192, 256))
16
+ input_image = (input_image / 255.0)
17
+ input_image = np.expand_dims(input_image, axis=0)
18
+
19
+ # Faça a previsão
20
+ prediction = model.predict(input_image)
21
+ class_index = np.argmax(prediction)
22
+ predicted_class = class_labels[class_index]
23
+
24
+ # Crie uma cópia da imagem de entrada para exibir
25
+ output_image = input_image[0].copy()
26
+ output_image = (output_image * 255).astype('uint8')
27
+
28
+ # Desenhe uma caixa de detecção na imagem
29
+ cv2.putText(output_image, predicted_class, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
30
+ timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
31
+ cv2.putText(output_image, timestamp, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
32
+
33
+ return output_image
34
+
35
+ # Configurar a interface Gradio
36
+ gr.Interface(
37
+ fn=classify_image,
38
+ inputs="image",
39
+ outputs="image",
40
+ live=True
41
+ ).launch()