DHEIVER commited on
Commit
0596f27
·
1 Parent(s): 23d807c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -83
app.py CHANGED
@@ -3,86 +3,60 @@ import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
  import cv2
6
- import datetime # Importe o módulo datetime
7
-
8
- # Defina a camada personalizada FixedDropout
9
- class FixedDropout(tf.keras.layers.Dropout):
10
- def _get_noise_shape(self, inputs):
11
- if self.noise_shape is None:
12
- return self.noise_shape
13
- symbolic_shape = tf.shape(inputs)
14
- noise_shape = [symbolic_shape[axis] if shape is None else shape
15
- for axis, shape in enumerate(self.noise_shape)]
16
- return tuple(noise_shape)
17
-
18
- # Registre a camada personalizada FixedDropout
19
- tf.keras.utils.get_custom_objects()['FixedDropout'] = FixedDropout
20
-
21
- # Carregue seu modelo TensorFlow treinado
22
- with tf.keras.utils.custom_object_scope({'FixedDropout': FixedDropout}):
23
- model = tf.keras.models.load_model('modelo_treinado.h5')
24
-
25
- # Defina uma função para fazer previsões
26
- def classify_image(input_image):
27
- # Log da forma da entrada
28
- print(f"Forma da entrada: {input_image.shape}")
29
-
30
- # Redimensione a imagem para as dimensões corretas (192x256)
31
- input_image = tf.image.resize(input_image, (192, 256)) # Redimensione para as dimensões esperadas
32
- input_image = (input_image / 255.0) # Normalize para [0, 1]
33
- input_image = np.expand_dims(input_image, axis=0) # Adicione a dimensão de lote
34
-
35
- # Log da forma da entrada após o redimensionamento
36
- print(f"Forma da entrada após o redimensionamento: {input_image.shape}")
37
-
38
- # Obtenha o tempo atual
39
- current_time = datetime.datetime.now()
40
-
41
- # Faça a previsão usando o modelo
42
- prediction = model.predict(input_image)
43
-
44
- # Assumindo que o modelo retorna probabilidades para duas classes, você pode retornar a classe com a maior probabilidade
45
- class_index = np.argmax(prediction)
46
- class_labels = ["Normal", "Cataract"] # Substitua pelas suas etiquetas de classe reais
47
- predicted_class = class_labels[class_index]
48
-
49
- # Crie uma imagem composta com o rótulo de previsão
50
- output_image = (input_image[0] * 255).astype('uint8')
51
-
52
- # Adicione espaço para o rótulo de previsão na parte inferior da imagem
53
- output_image = cv2.copyMakeBorder(output_image, 0, 50, 0, 0, cv2.BORDER_CONSTANT, value=(255, 255, 255))
54
-
55
- # Desenhe um retângulo branco como fundo para o rótulo
56
- label_background = np.ones((50, output_image.shape[1], 3), dtype=np.uint8) * 255
57
-
58
- # Coloque o texto do rótulo e a caixa dentro do fundo branco
59
- output_image[-50:] = label_background
60
-
61
- # Escreva o rótulo de previsão na imagem
62
- font = cv2.FONT_HERSHEY_SIMPLEX
63
- font_scale = 0.4 # Tamanho da fonte reduzido
64
- cv2.putText(output_image, f"Analysis Time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}", (10, output_image.shape[0] - 30), font, font_scale, (0, 0, 0), 1)
65
- cv2.putText(output_image, f"Predicted Class: {predicted_class}", (10, output_image.shape[0] - 10), font, font_scale, (0, 0, 0), 1) # Cor preta
66
-
67
- # Calcule as coordenadas para centralizar a caixa azul no centro da imagem
68
- image_height, image_width, _ = output_image.shape
69
- box_size = 100 # Tamanho da caixa azul (ajuste conforme necessário)
70
- box_x = (image_width - box_size) // 2
71
- box_y = (image_height - box_size) // 2
72
-
73
- # Desenhe uma caixa de identificação de objeto (retângulo azul) centralizada
74
- object_box_color = (255, 0, 0) # Azul (BGR)
75
- cv2.rectangle(output_image, (box_x, box_y), (box_x + box_size, box_y + box_size), object_box_color, 2) # Caixa centralizada
76
-
77
- return output_image
78
-
79
- # Crie uma interface Gradio
80
- input_interface = gr.Interface(
81
- fn=classify_image,
82
- inputs="image", # Especifique o tipo de entrada como "image"
83
- outputs="image", # Especifique o tipo de saída como "image"
84
- live=True
85
- )
86
-
87
- # Inicie o aplicativo Gradio
88
- input_interface.launch()
 
3
  import numpy as np
4
  from PIL import Image
5
  import cv2
6
+ import datetime
7
+
8
+ class ImageClassifierApp:
9
+ def __init__(self, model_path):
10
+ self.model_path = model_path
11
+ self.model = self.load_model()
12
+ self.class_labels = ["Normal", "Cataract"]
13
+
14
+ def load_model(self):
15
+ # Load the trained TensorFlow model
16
+ with tf.keras.utils.custom_object_scope({'FixedDropout': FixedDropout}):
17
+ model = tf.keras.models.load_model(self.model_path)
18
+ return model
19
+
20
+ def classify_image(self, input_image):
21
+ input_image = tf.image.resize(input_image, (192, 256))
22
+ input_image = (input_image / 255.0)
23
+ input_image = np.expand_dims(input_image, axis=0)
24
+
25
+ current_time = datetime.datetime.now()
26
+ prediction = self.model.predict(input_image)
27
+ class_index = np.argmax(prediction)
28
+ predicted_class = self.class_labels[class_index]
29
+
30
+ output_image = (input_image[0] * 255).astype('uint8')
31
+ output_image = cv2.copyMakeBorder(output_image, 0, 50, 0, 0, cv2.BORDER_CONSTANT, value=(255, 255, 255))
32
+ label_background = np.ones((50, output_image.shape[1], 3), dtype=np.uint8) * 255
33
+ output_image[-50:] = label_background
34
+
35
+ font = cv2.FONT_HERSHEY_SIMPLEX
36
+ font_scale = 0.4
37
+ cv2.putText(output_image, f"Analysis Time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}", (10, output_image.shape[0] - 30), font, font_scale, (0, 0, 0), 1)
38
+ cv2.putText(output_image, f"Predicted Class: {predicted_class}", (10, output_image.shape[0] - 10), font, font_scale, (0, 0, 0), 1)
39
+
40
+ image_height, image_width, _ = output_image.shape
41
+ box_size = 100
42
+ box_x = (image_width - box_size) // 2
43
+ box_y = (image_height - box_size) // 2
44
+ object_box_color = (255, 0, 0)
45
+ cv2.rectangle(output_image, (box_x, box_y), (box_x + box_size, box_y + box_size), object_box_color, 2)
46
+
47
+ return output_image
48
+
49
+ def run_interface(self):
50
+ input_interface = gr.Interface(
51
+ fn=self.classify_image,
52
+ inputs="image",
53
+ outputs="image",
54
+ live=True
55
+ )
56
+ input_interface.launch()
57
+
58
+
59
+ if __name__ == "__main__":
60
+ model_path = 'modelo_treinado.h5' # Substitua pelo caminho para o seu modelo treinado
61
+ app = ImageClassifierApp(model_path)
62
+ app.run_interface()