File size: 2,410 Bytes
fa2a7b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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),  # Adjust input size based on image size
            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')
    ## give the weights trained
    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')))

    ## put the model in evaluation mode
    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))
    ])

    ## transform the img like the training image
    input_img = transform_pipeline(image).unsqueeze(0)
    # input_img

    ## define the label by index
    class_to_label = {0: 'glioma', 1: 'meningioma', 2: 'notumor', 3: 'pituitary'}

    ## run the model
    with torch.no_grad():
        output = model_load(input_img)

    ## convert to the softmax for getting percent each label
    probabilities = F.softmax(output, dim=1)

    ## get predicted label with highest value
    _, predicted_label = torch.max(probabilities,1)
    # confidence_percent = probabilities[0].tolist()[predicted_label.item()]
    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)