megiddo commited on
Commit
f3105a4
·
verified ·
1 Parent(s): 99d0d3f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import models, transforms
3
+ from PIL import Image
4
+
5
+
6
+ labels = {
7
+ 0: "bluebell",
8
+ 1: "buttercup",
9
+ 2: "colts_foot",
10
+ 3: "corn_poppy",
11
+ 4: "cowslip",
12
+ 5: "crocus",
13
+ 6: "daffodil",
14
+ 7: "daisy",
15
+ 8: "dandelion",
16
+ 9: "foxglove",
17
+ 10: "fritillary",
18
+ 11: "geranium",
19
+ 12: "hibiscus",
20
+ 13: "iris",
21
+ 14: "lily_valley",
22
+ 15: "pansy",
23
+ 16: "petunia",
24
+ 17: "rose",
25
+ 18: "snowdrop",
26
+ 19: "sunflower",
27
+ 20: "tigerlily",
28
+ 21: "tulip",
29
+ 22: "wallflower",
30
+ 23: "water_lily",
31
+ 24: "wild_tulip",
32
+ 25: "windflower"
33
+ }
34
+
35
+ # Load the trained ResNet-152 model
36
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
37
+
38
+ # Load model structure
39
+ model = models.resnet152()
40
+ num_classes = 26 # Update with your dataset's number of classes
41
+ model.fc = torch.nn.Linear(model.fc.in_features, num_classes)
42
+
43
+ # Load trained weights
44
+ model.load_state_dict(torch.load('trained_model.pth', map_location=device))
45
+ model = model.to(device)
46
+ model.eval() # Set to evaluation mode
47
+
48
+ # Preprocessing pipeline for incoming images
49
+ preprocess = transforms.Compose([
50
+ transforms.Resize((224, 224)), # ResNet default input size
51
+ transforms.ToTensor(),
52
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
53
+ ])
54
+
55
+ def predict_image(image_path):
56
+ # Load and preprocess the image
57
+ image = Image.open(image_path).convert("RGB")
58
+ input_tensor = preprocess(image).unsqueeze(0).to(device)
59
+
60
+ # Predict
61
+ with torch.no_grad():
62
+ outputs = model(input_tensor)
63
+ _, predicted_class = torch.max(outputs, 1)
64
+
65
+ return predicted_class.item() # Return class index
66
+
67
+ import gradio as gr
68
+
69
+ def get_class_name(class_index):
70
+ return labels[class_index]
71
+ # Function to predict from an uploaded image
72
+ def classify_image(image):
73
+ predicted_class = predict_image(image) # Use the function from above
74
+ return f"Predicted Class: {predicted_class} : {get_class_name(predicted_class)}"
75
+
76
+ # Create Gradio interface
77
+ interface = gr.Interface(
78
+ fn=classify_image,
79
+ inputs=gr.Image(type="filepath"), # Accept image uploads
80
+ outputs="text",
81
+ title="Image Classification with ResNet-152",
82
+ description="Upload an image to classify it into one of 26 classes."
83
+ )
84
+
85
+ # Launch the app
86
+ interface.launch()