File size: 2,203 Bytes
5d88333
 
 
 
 
 
 
 
 
90fa633
5d88333
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac514d1
 
5d88333
 
 
90fa633
350548c
 
 
 
 
5d88333
 
 
 
 
 
 
90fa633
5d88333
 
 
350548c
5d88333
 
90fa633
 
 
 
 
350548c
90fa633
 
 
 
5d88333
 
350548c
 
 
90fa633
350548c
90fa633
350548c
5d88333
 
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
import gradio as gr
import torch
import torch.nn as nn
from torchvision import transforms
from torchvision.models import swin_t
from PIL import Image

# πŸ”§ Model definition
class MMIM(nn.Module):
    def __init__(self, num_classes=9):
        super(MMIM, self).__init__()
        self.backbone = swin_t(weights='IMAGENET1K_V1')
        self.backbone.head = nn.Identity()
        self.classifier = nn.Sequential(
            nn.Linear(768, 512),
            nn.ReLU(),
            nn.Dropout(0.3),
            nn.Linear(512, num_classes)
        )

    def forward(self, x):
        features = self.backbone(x)
        return self.classifier(features)

# βœ… Load model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = MMIM(num_classes=12)
model.load_state_dict(torch.load("MMIM_best2.pth", map_location=device))
model.to(device)
model.eval()

# βœ… Updated class names (match folder structure)
class_names = [
    'Black grass', 'Charlock', 'Cleavers', 'Common Chickweed', 'Common Wheat',
    'Fat Hen', 'Loose Silky-bent', 'Maize', 'Scentless Mayweed',
    'Shepherds purse', 'Small-flowered Cranesbill', 'Sugar beet'
]

# πŸ” Image transform
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor()
])

# πŸ” Prediction function with negative detection
def predict(img):
    img = img.convert('RGB')
    img_tensor = transform(img).unsqueeze(0).to(device)

    with torch.no_grad():
        outputs = model(img_tensor)
        probs = torch.softmax(outputs, dim=1)
        conf, pred = torch.max(probs, 1)

    predicted_class = class_names[pred.item()]
    confidence = conf.item() * 100

    if predicted_class.lower() == "negative":
        return f"⚠️ This image is predicted as Negative.\nConfidence: {confidence:.2f}%"

    return f"βœ… Predicted as a weed with class-{predicted_class}\nConfidence: {confidence:.2f}%"

# 🎨 Gradio Interface
interface = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs="text",
    title="Weed Image Classifier",
    description="Upload a weed image to predict its class. If the model detects a non-weed image, it will return 'Negative'."
)

interface.launch()