|
import gradio as gr |
|
import torch |
|
from transformers import ViTFeatureExtractor, ViTForImageClassification |
|
from PIL import Image, ImageDraw, ImageFont |
|
import io |
|
import numpy as np |
|
|
|
|
|
model_name = "mrm8488/vit-base-patch16-224_finetuned-kvasirv2-colonoscopy" |
|
feature_extractor = ViTFeatureExtractor.from_pretrained(model_name) |
|
model = ViTForImageClassification.from_pretrained(model_name) |
|
|
|
|
|
id2label = { |
|
"0": "dyed-lifted-polyps", |
|
"1": "dyed-resection-margins", |
|
"2": "esophagitis", |
|
"3": "normal-cecum", |
|
"4": "normal-pylorus", |
|
"5": "normal-z-line", |
|
"6": "polyps", |
|
"7": "ulcerative-colitis" |
|
} |
|
|
|
|
|
def classify_image(input_image): |
|
|
|
inputs = feature_extractor(input_image, return_tensors="pt") |
|
|
|
outputs = model(**inputs) |
|
|
|
predicted_class_id = torch.argmax(outputs.logits, dim=1).item() |
|
|
|
predicted_class_label = id2label.get(str(predicted_class_id), "Desconhecido") |
|
|
|
|
|
image = Image.fromarray(input_image.astype('uint8')) |
|
|
|
|
|
width, height = image.size |
|
|
|
|
|
result_image = Image.new('RGB', (width, height + 40), color='white') |
|
result_image.paste(image, (0, 0)) |
|
|
|
|
|
draw = ImageDraw.Draw(result_image) |
|
font = ImageFont.load_default() |
|
text = f'Previsão: {predicted_class_label}' |
|
text_width, text_height = draw.textsize(text, font=font) |
|
x = (width - text_width) // 2 |
|
y = height + 10 |
|
draw.text((x, y), text, fill='black', font=font) |
|
|
|
|
|
result_image = np.array(result_image) |
|
return result_image |
|
|
|
|
|
interface = gr.Interface( |
|
fn=classify_image, |
|
inputs=gr.inputs.Image(type="numpy", label="Carregar uma imagem"), |
|
outputs=gr.outputs.Image(type="numpy", label="Resultado"), |
|
title="Classificador de Imagem ViT", |
|
description="Esta aplicação Gradio permite classificar imagens usando um modelo Vision Transformer (ViT). O rótulo da previsão está na parte inferior da imagem de saída em uma faixa branca." |
|
) |
|
|
|
|
|
interface.launch() |
|
|