DHEIVER commited on
Commit
c8fb571
1 Parent(s): 7311684

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -56
app.py CHANGED
@@ -1,98 +1,68 @@
1
  import tensorflow as tf
2
  import efficientnet.tfkeras as efn
3
- from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dense
4
  import numpy as np
5
  import gradio as gr
6
- from PIL import Image, ImageDraw, ImageFont
7
 
8
  # Dimensões da imagem
9
  IMG_HEIGHT = 224
10
  IMG_WIDTH = 224
11
 
12
- # Função para construir o modelo de detecção de objetos
13
- def build_object_detection_model(img_height, img_width):
14
- # Replace this with your object detection model architecture and weights
15
- # For example, you can use a model from TensorFlow Hub or any other source
16
- object_detection_model = None # Load your object detection model here
17
- return object_detection_model
18
-
19
- # Função para construir o modelo de classificação
20
- def build_classification_model(img_height, img_width, n):
21
- inp = Input(shape=(img_height, img_width, n))
22
  efnet = efn.EfficientNetB0(
23
  input_shape=(img_height, img_width, n),
24
  weights='imagenet',
25
  include_top=False
26
  )
27
  x = efnet(inp)
28
- x = GlobalAveragePooling2D()(x)
29
- x = Dense(2, activation='softmax')(x)
30
  model = tf.keras.Model(inputs=inp, outputs=x)
31
  opt = tf.keras.optimizers.Adam(learning_rate=0.000003)
32
  loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.01)
33
  model.compile(optimizer=opt, loss=loss, metrics=['accuracy'])
34
  return model
35
 
36
- # Load the object detection and classification models
37
- object_detection_model = build_object_detection_model(IMG_HEIGHT, IMG_WIDTH)
38
- classification_model = build_classification_model(IMG_HEIGHT, IMG_WIDTH, 3)
39
- classification_model.load_weights('modelo_treinado.h5')
40
 
41
- # Function to preprocess the image for classification
42
  def preprocess_image(input_image):
 
43
  input_image = tf.image.resize(input_image, (IMG_HEIGHT, IMG_WIDTH))
 
 
44
  input_image = input_image / 255.0
 
 
 
45
  return input_image
46
 
47
- # Function to perform object detection and classification
48
  def predict_image(input_image):
49
  # Realize o pré-processamento na imagem de entrada
50
- input_image_classification = preprocess_image(input_image)
51
 
52
- # Faça uma previsão usando o modelo de classificação carregado
53
- input_image_classification = tf.expand_dims(input_image_classification, axis=0)
54
- classification_prediction = classification_model.predict(input_image_classification)
55
-
56
- # Perform object detection here using the object_detection_model
57
- # Replace this with your object detection logic to get bounding box coordinates
58
 
59
  # A saída será uma matriz de previsões (no caso de classificação de duas classes, será algo como [[probabilidade_classe_0, probabilidade_classe_1]])
60
  # Adicione lógica para interpretar o resultado e formatá-lo para exibição
61
-
62
  class_names = ["Normal", "Cataract"]
63
- predicted_class = class_names[np.argmax(classification_prediction)]
64
- probability = classification_prediction[0][np.argmax(classification_prediction)]
65
-
66
- # You can format the result with object detection bounding box and label here
67
- # For example:
68
- # formatted_text = f"Predicted Class: {predicted_class}\nProbability: {probability:.2%}\nObject Detection: {bounding_box_coordinates}"
69
-
70
- # Create an output image with object detection
71
- output_image = input_image # Replace this with your object detection visualization
72
-
73
- # Convert the output image to bytes
74
- output_image_bytes = Image.fromarray(np.uint8(output_image * 255))
75
-
76
- # Create an image with the label "Normal" or "Cataract" outside the image
77
- draw = ImageDraw.Draw(output_image_bytes)
78
- font = ImageFont.load_default() # You can customize the font and size here
79
- label_text = f"Predicted Class: {predicted_class}"
80
- label_size = draw.textsize(label_text, font=font)
81
- label_position = (10, 10) # You can adjust the label position
82
- draw.rectangle([label_position, (label_position[0] + label_size[0], label_position[1] + label_size[1])], fill="white")
83
- draw.text(label_position, label_text, fill="black", font=font)
84
-
85
- # Convert the image with the label to bytes
86
- labeled_image_bytes = output_image_bytes.tobytes()
87
 
88
- # Return both the image with object detection and the labeled image
89
- return [labeled_image_bytes, f"Predicted Class: {predicted_class}"]
90
 
91
  # Crie uma interface Gradio para fazer previsões
92
  iface = gr.Interface(
93
  fn=predict_image,
94
- inputs=gr.inputs.Image(label="Upload an Image", type="filepath"),
95
- outputs=[gr.outputs.Image(type="pil"), gr.outputs.Text(label="Prediction", type="markdown")],
96
  interpretation="default"
97
  )
98
 
 
1
  import tensorflow as tf
2
  import efficientnet.tfkeras as efn
 
3
  import numpy as np
4
  import gradio as gr
 
5
 
6
  # Dimensões da imagem
7
  IMG_HEIGHT = 224
8
  IMG_WIDTH = 224
9
 
10
+ # Função para construir o modelo
11
+ def build_model(img_height, img_width, n):
12
+ inp = tf.keras.layers.Input(shape=(img_height, img_width, n))
 
 
 
 
 
 
 
13
  efnet = efn.EfficientNetB0(
14
  input_shape=(img_height, img_width, n),
15
  weights='imagenet',
16
  include_top=False
17
  )
18
  x = efnet(inp)
19
+ x = tf.keras.layers.GlobalAveragePooling2D()(x)
20
+ x = tf.keras.layers.Dense(2, activation='softmax')(x)
21
  model = tf.keras.Model(inputs=inp, outputs=x)
22
  opt = tf.keras.optimizers.Adam(learning_rate=0.000003)
23
  loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.01)
24
  model.compile(optimizer=opt, loss=loss, metrics=['accuracy'])
25
  return model
26
 
27
+ # Carregue o modelo treinado
28
+ loaded_model = build_model(IMG_HEIGHT, IMG_WIDTH, 3)
29
+ loaded_model.load_weights('modelo_treinado.h5')
 
30
 
31
+ # Função para realizar o pré-processamento da imagem de entrada
32
  def preprocess_image(input_image):
33
+ # Redimensione a imagem para as dimensões esperadas pelo modelo
34
  input_image = tf.image.resize(input_image, (IMG_HEIGHT, IMG_WIDTH))
35
+
36
+ # Normalização dos valores de pixel para o intervalo [0, 1]
37
  input_image = input_image / 255.0
38
+
39
+ # Outras transformações, se necessárias (por exemplo, normalização adicional)
40
+
41
  return input_image
42
 
43
+ # Função para fazer previsões usando o modelo treinado
44
  def predict_image(input_image):
45
  # Realize o pré-processamento na imagem de entrada
46
+ input_image = preprocess_image(input_image)
47
 
48
+ # Faça uma previsão usando o modelo carregado
49
+ input_image = tf.expand_dims(input_image, axis=0)
50
+ prediction = loaded_model.predict(input_image)
 
 
 
51
 
52
  # A saída será uma matriz de previsões (no caso de classificação de duas classes, será algo como [[probabilidade_classe_0, probabilidade_classe_1]])
53
  # Adicione lógica para interpretar o resultado e formatá-lo para exibição
 
54
  class_names = ["Normal", "Cataract"]
55
+ predicted_class = class_names[np.argmax(prediction)]
56
+ probability = prediction[0][np.argmax(prediction)]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ formatted_text = f"Predicted Class: {predicted_class}\nProbability: {probability:.2%}"
59
+ return formatted_text
60
 
61
  # Crie uma interface Gradio para fazer previsões
62
  iface = gr.Interface(
63
  fn=predict_image,
64
+ inputs=gr.inputs.Image(label="Upload an Image", type="pil"),
65
+ outputs=gr.outputs.Textbox(label="Prediction", type="text"),
66
  interpretation="default"
67
  )
68