|
import torch |
|
import torch.nn.functional as F |
|
import torchvision.transforms as transforms |
|
import numpy as np |
|
import gradio as gr |
|
from torch import nn |
|
from gradio import components |
|
from PIL import Image |
|
|
|
class BrainTumorClassifier(nn.Module): |
|
def __init__(self, num_classes): |
|
super(BrainTumorClassifier, self).__init__() |
|
self.features = nn.Sequential( |
|
nn.Conv2d(3, 20, kernel_size=3, padding=1), |
|
nn.ReLU(), |
|
nn.MaxPool2d(2, 2), |
|
nn.Conv2d(20, 32, kernel_size=3, padding=1), |
|
nn.ReLU(), |
|
nn.MaxPool2d(2, 2) |
|
) |
|
self.classifier = nn.Sequential( |
|
nn.Linear(32 * 56 * 56, 128), |
|
nn.ReLU(), |
|
nn.Linear(128, num_classes) |
|
) |
|
|
|
def forward(self, x): |
|
x = self.features(x) |
|
x = x.view(-1, 32 * 56 * 56) |
|
x = self.classifier(x) |
|
return x |
|
|
|
def predict(image): |
|
image = Image.fromarray(np.uint8(image)).convert('RGB') |
|
|
|
model_path = 'cnn_tumorbrain_classifier_self.pth' |
|
model_load = BrainTumorClassifier(4) |
|
model_load.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))) |
|
|
|
|
|
model_load.eval() |
|
|
|
transform_pipeline = transforms.Compose([ |
|
transforms.Resize((224,224)), |
|
transforms.ToTensor(), |
|
transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)) |
|
]) |
|
|
|
|
|
input_img = transform_pipeline(image).unsqueeze(0) |
|
|
|
|
|
|
|
class_to_label = {0: 'glioma', 1: 'meningioma', 2: 'notumor', 3: 'pituitary'} |
|
|
|
|
|
with torch.no_grad(): |
|
output = model_load(input_img) |
|
|
|
|
|
probabilities = F.softmax(output, dim=1) |
|
|
|
|
|
_, predicted_label = torch.max(probabilities,1) |
|
|
|
conf, _ = torch.max(probabilities, 1) |
|
|
|
result = "{}, with confidence level in {}%".format(class_to_label[predicted_label.item()], conf.item()*100) |
|
return result |
|
|
|
iface = gr.Interface(fn=predict, |
|
inputs=gr.Image(), |
|
outputs="textbox") |
|
|
|
iface.launch(share=True) |