BlueSR commited on
Commit
2729af1
·
verified ·
1 Parent(s): 67f758d

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +133 -0
  2. best_cnn_model.pth +3 -0
  3. requirements.txt +7 -0
  4. rf_model.pkl +3 -0
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision import transforms
4
+ from torchvision.models import efficientnet_b0
5
+ import gradio as gr
6
+ import numpy as np
7
+ import pickle
8
+ import os
9
+ from PIL import Image
10
+
11
+ # Constants
12
+ NUM_CLASSES = 4
13
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ CLASS_NAMES = ["Good_condition", "Potholes", "Cracked_road", "Flooded_muddy"]
15
+
16
+ # Load the CNN model
17
+ def load_cnn_model():
18
+ # Build model architecture (same as in train_cnn.py)
19
+ model = efficientnet_b0(weights=None)
20
+
21
+ # Replace classifier
22
+ in_features = model.classifier[1].in_features
23
+ model.classifier = nn.Sequential(
24
+ nn.Linear(in_features, 256),
25
+ nn.BatchNorm1d(256),
26
+ nn.ReLU(),
27
+ nn.Dropout(p=0.2),
28
+ nn.Linear(256, NUM_CLASSES)
29
+ )
30
+
31
+ # Load the saved weights
32
+ model.load_state_dict(torch.load("best_cnn_model.pth", map_location=DEVICE))
33
+ model.to(DEVICE)
34
+ model.eval()
35
+ return model
36
+
37
+ # Load the Random Forest model
38
+ def load_rf_model():
39
+ with open("rf_model.pkl", "rb") as f:
40
+ return pickle.load(f)
41
+
42
+ # Preprocess image for CNN
43
+ def preprocess_image_cnn(image):
44
+ preprocess = transforms.Compose([
45
+ transforms.Resize((224, 224)),
46
+ transforms.ToTensor(),
47
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
48
+ ])
49
+ return preprocess(image).unsqueeze(0)
50
+
51
+ # Preprocess image for RF
52
+ def preprocess_image_rf(image):
53
+ # Convert to numpy, resize, and flatten
54
+ image = image.resize((64, 64))
55
+ image_array = np.array(image)
56
+ # If grayscale, expand to RGB
57
+ if len(image_array.shape) == 2:
58
+ image_array = np.stack([image_array] * 3, axis=2)
59
+ # Flatten the image
60
+ return image_array.reshape(1, -1)
61
+
62
+ # Prediction function
63
+ def predict(img, model_choice, cnn_model, rf_model):
64
+ if img is None:
65
+ return "No image provided", "Please upload an image"
66
+
67
+ try:
68
+ if model_choice == "CNN":
69
+ # Preprocess for CNN
70
+ img_tensor = preprocess_image_cnn(img)
71
+ img_tensor = img_tensor.to(DEVICE)
72
+
73
+ # Get prediction
74
+ with torch.no_grad():
75
+ outputs = cnn_model(img_tensor)
76
+ probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
77
+ predicted_class = torch.argmax(probabilities).item()
78
+
79
+ # Format confidence scores
80
+ confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i].item()*100:.2f}%"
81
+ for i in range(len(CLASS_NAMES))}
82
+ confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
83
+
84
+ return CLASS_NAMES[predicted_class], confidence_text
85
+
86
+ else: # Random Forest
87
+ # Preprocess for RF
88
+ img_features = preprocess_image_rf(img)
89
+
90
+ # Get prediction
91
+ predicted_class = rf_model.predict(img_features)[0]
92
+ probabilities = rf_model.predict_proba(img_features)[0]
93
+
94
+ # Format confidence scores
95
+ confidence_scores = {CLASS_NAMES[i]: f"{probabilities[i]*100:.2f}%"
96
+ for i in range(len(CLASS_NAMES))}
97
+ confidence_text = "\n".join([f"{cls}: {score}" for cls, score in confidence_scores.items()])
98
+
99
+ return CLASS_NAMES[predicted_class], confidence_text
100
+
101
+ except Exception as e:
102
+ return f"Error: {str(e)}", "An error occurred during prediction."
103
+
104
+ # Load models
105
+ cnn_model = load_cnn_model()
106
+ rf_model = load_rf_model()
107
+
108
+ # Create Gradio interface
109
+ with gr.Blocks() as demo:
110
+ gr.Markdown("## Road Surface Classification")
111
+
112
+ with gr.Row():
113
+ with gr.Column():
114
+ image_input = gr.Image(type="pil", label="Upload Road Image")
115
+ model_selector = gr.Radio(choices=["CNN", "Random Forest"], value="CNN", label="Select Model")
116
+ classify_btn = gr.Button("Classify")
117
+ with gr.Column():
118
+ label_output = gr.Textbox(label="Predicted Class")
119
+ confidence_output = gr.Textbox(label="Confidence Scores", lines=5)
120
+
121
+ classify_btn.click(
122
+ fn=lambda img, model_choice: predict(img, model_choice, cnn_model, rf_model),
123
+ inputs=[image_input, model_selector],
124
+ outputs=[label_output, confidence_output]
125
+ )
126
+
127
+ gr.Markdown("### How to use")
128
+ gr.Markdown("1. Upload a road image")
129
+ gr.Markdown("2. Select either CNN or Random Forest model")
130
+ gr.Markdown("3. Click 'Classify' to get the prediction")
131
+
132
+ # Launch the app
133
+ demo.launch()
best_cnn_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af969e9134d16feea50408729e428e59ad3e32706de3ed9816ab87cbd1de4cb7
3
+ size 17652985
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ numpy
4
+ scikit-learn
5
+ pillow
6
+ matplotlib
7
+ gradio
rf_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef8d2f2db4e5caaa29140cacf2d4cbd1d959750e5ff722119037af62432d8af9
3
+ size 947289