DHEIVER's picture
Update app.py
2cc1c9f
raw
history blame
2.6 kB
import tensorflow as tf
import efficientnet.tfkeras as efn
from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dense
import numpy as np
import gradio as gr
# Dimensões da imagem
IMG_HEIGHT = 224
IMG_WIDTH = 224
# Função para construir o modelo
def build_model(img_height, img_width, n):
inp = Input(shape=(img_height, img_width, n))
efnet = efn.EfficientNetB0(
input_shape=(img_height, img_width, n),
weights='imagenet',
include_top=False
)
x = efnet(inp)
x = GlobalAveragePooling2D()(x)
x = Dense(2, activation='softmax')(x)
model = tf.keras.Model(inputs=inp, outputs=x)
opt = tf.keras.optimizers.Adam(learning_rate=0.000003)
loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing=0.01)
model.compile(optimizer=opt, loss=loss, metrics=['accuracy'])
return model
# Carregue o modelo treinado
loaded_model = build_model(IMG_HEIGHT, IMG_WIDTH, 3)
loaded_model.load_weights('modelo_treinado.h5')
# Function to preprocess the uploaded image
def preprocess_uploaded_image(input_image):
input_image = tf.image.decode_image(input_image.read(), channels=3)
input_image = tf.image.resize(input_image, (IMG_HEIGHT, IMG_WIDTH))
input_image = input_image / 255.0
return input_image
# Função para fazer previsões usando o modelo treinado
def predict_image(input_image):
# Realize o pré-processamento na imagem de entrada
input_image = preprocess_image(input_image)
# Faça uma previsão usando o modelo carregado
input_image = tf.expand_dims(input_image, axis=0)
prediction = loaded_model.predict(input_image)
# 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]])
# Adicione lógica para interpretar o resultado e formatá-lo para exibição
class_names = ["Normal", "Cataract"]
predicted_class = class_names[np.argmax(prediction)]
probability = prediction[0][np.argmax(prediction)]
formatted_text = f"Predicted Class: {predicted_class}\nProbability: {probability:.2%}"
return formatted_text
# Crie uma interface Gradio para fazer previsões
iface = gr.Interface(
fn=predict_image,
inputs=gr.inputs.Image(label="Upload an Image", type="file"),
outputs=gr.outputs.Text(label="Prediction", type="markdown"),
interpretation="default",
title="Image Classifier",
description="Upload an image to classify it as 'Normal' or 'Cataract'.",
theme="compact",
loading="circle"
)
# Execute a interface Gradio
iface.launch()