Spaces:
Build error
Build error
| import gradio as gr | |
| import tensorflow as tf | |
| import numpy as np | |
| from PIL import Image | |
| import cv2 | |
| # Defina a camada personalizada FixedDropout | |
| class FixedDropout(tf.keras.layers.Dropout): | |
| def _get_noise_shape(self, inputs): | |
| if self.noise_shape is None: | |
| return self.noise_shape | |
| symbolic_shape = tf.shape(inputs) | |
| noise_shape = [symbolic_shape[axis] if shape is None else shape | |
| for axis, shape in enumerate(self.noise_shape)] | |
| return tuple(noise_shape) | |
| # Registre a camada personalizada FixedDropout | |
| tf.keras.utils.get_custom_objects()['FixedDropout'] = FixedDropout | |
| # Carregue seu modelo TensorFlow treinado | |
| with tf.keras.utils.custom_object_scope({'FixedDropout': FixedDropout}): | |
| model = tf.keras.models.load_model('modelo_treinado.h5') | |
| # Defina uma função para fazer previsões | |
| def classify_image(input_image): | |
| # Log da forma da entrada | |
| print(f"Forma da entrada: {input_image.shape}") | |
| # Redimensione a imagem para as dimensões corretas (192x256) | |
| input_image = tf.image.resize(input_image, (192, 256)) # Redimensione para as dimensões esperadas | |
| input_image = (input_image / 255.0) # Normalize para [0, 1] | |
| input_image = np.expand_dims(input_image, axis=0) # Adicione a dimensão de lote | |
| # Log da forma da entrada após o redimensionamento | |
| print(f"Forma da entrada após o redimensionamento: {input_image.shape}") | |
| # Faça a previsão usando o modelo | |
| prediction = model.predict(input_image) | |
| # Assumindo que o modelo retorna probabilidades para duas classes, você pode retornar a classe com a maior probabilidade | |
| class_index = np.argmax(prediction) | |
| class_labels = ["Normal", "Cataract"] # Substitua pelas suas etiquetas de classe reais | |
| predicted_class = class_labels[class_index] | |
| # Crie uma imagem composta com a caixa de identificação de objeto e o rótulo de previsão | |
| output_image = (input_image[0] * 255).astype('uint8') | |
| output_image_with_box = output_image.copy() | |
| # Desenhe uma caixa de identificação de objeto no output_image_with_box (centralizada e maior) | |
| if predicted_class == "Cataract": # Adicione sua lógica para desenhar a caixa com base na classe | |
| image_height, image_width, _ = output_image.shape | |
| box_size = min(image_height, image_width) // 2 | |
| x1 = (image_width - box_size) // 2 | |
| y1 = (image_height - box_size) // 2 | |
| x2 = x1 + box_size | |
| y2 = y1 + box_size | |
| cv2.rectangle(output_image_with_box, (x1, y1), (x2, y2), (0, 255, 0), 2) # Caixa verde | |
| # Escreva o rótulo de previsão no output_image_with_box (com a cor da caixa e estatísticas) | |
| font = cv2.FONT_HERSHEY_SIMPLEX | |
| font_scale = 0.4 # Tamanho da fonte reduzido | |
| cv2.putText(output_image_with_box, f"Predicted Class: {predicted_class}", (10, 20), font, font_scale, (0, 255, 0), 1) # Cor verde | |
| # Adicione estatísticas (substitua com suas próprias estatísticas) | |
| stats = f"Accuracy: {prediction[0][class_index]:.2f}, Confidence: {prediction[0].max():.2f}" | |
| cv2.putText(output_image_with_box, stats, (10, 40), font, font_scale, (0, 255, 0), 1) | |
| return output_image_with_box | |
| # Crie uma interface Gradio | |
| input_interface = gr.Interface( | |
| fn=classify_image, | |
| inputs="image", # Especifique o tipo de entrada como "image" | |
| outputs="image", # Especifique o tipo de saída como "image" | |
| live=True | |
| ) | |
| # Inicie o aplicativo Gradio | |
| input_interface.launch() | |