Sarvamangalak commited on
Commit
91f812e
Β·
verified Β·
1 Parent(s): df0733b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +230 -123
app.py CHANGED
@@ -1,144 +1,251 @@
1
  import gradio as gr
2
- import cv2
3
- import numpy as np
4
- import easyocr
5
- from ultralytics import YOLO
6
- import re
7
-
8
- # Load models
9
- model = YOLO("best.pt") # your trained number plate model
10
- reader = easyocr.Reader(['en'])
11
-
12
- ############################################################
13
- # Image Enhancement for Night Images
14
- ############################################################
15
-
16
- def enhance_image(image):
17
- lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
18
- l, a, b = cv2.split(lab)
19
-
20
- clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
21
- cl = clahe.apply(l)
22
-
23
- enhanced = cv2.merge((cl,a,b))
24
- enhanced = cv2.cvtColor(enhanced, cv2.COLOR_LAB2BGR)
25
-
26
- return enhanced
27
-
28
-
29
- ############################################################
30
- # Indian Plate Colour Classification
31
- ############################################################
32
-
33
- def classify_plate_color(roi):
34
-
35
- hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
36
-
37
- masks = {
38
- "white": cv2.inRange(hsv, np.array([0,0,180]), np.array([180,60,255])),
39
- "yellow": cv2.inRange(hsv, np.array([15,80,80]), np.array([40,255,255])),
40
- "green": cv2.inRange(hsv, np.array([35,50,50]), np.array([85,255,255]))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  }
42
-
43
- color_counts = {color: np.sum(mask) for color, mask in masks.items()}
44
- dominant_color = max(color_counts, key=color_counts.get)
45
-
46
- if dominant_color == "white":
47
- return "Private Vehicle", False
48
- elif dominant_color == "yellow":
49
- return "Commercial Vehicle", False
50
- elif dominant_color == "green":
51
- return "Electric Vehicle (EV)", True
52
- else:
53
- return "Unknown", False
54
-
55
-
56
- ############################################################
57
- # Main Detection Pipeline
58
- ############################################################
59
-
60
- def detect_number_plates(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  if image is None:
63
- return None, "Upload image first."
64
-
65
- img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
66
-
67
- # Night enhancement
68
- img = enhance_image(img)
69
-
70
- results = model(img)
71
-
72
- detected_info = []
73
-
74
- for result in results:
75
- boxes = result.boxes.xyxy.cpu().numpy()
76
-
77
- for box in boxes:
78
- x1, y1, x2, y2 = map(int, box)
79
-
80
- plate_roi = img[y1:y2, x1:x2]
81
-
82
- # OCR
83
- ocr_results = reader.readtext(plate_roi)
84
-
85
- plate_number = "Unknown"
86
- for res in ocr_results:
87
- text = re.sub(r'[^A-Z0-9]', '', res[1].upper())
88
- if len(text) >= 8:
89
- plate_number = text
90
- break
91
-
92
- vehicle_type, is_ev = classify_plate_color(plate_roi)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- if is_ev:
95
- benefit = "EV Benefits: Toll & Parking Discount"
96
- else:
97
- benefit = "No EV Benefits"
98
 
99
- # Draw bounding box
100
- cv2.rectangle(img, (x1,y1), (x2,y2), (0,255,0), 2)
 
101
 
102
- label = f"{plate_number} | {vehicle_type}"
103
- cv2.putText(img, label,
104
- (x1, y1-10),
105
- cv2.FONT_HERSHEY_SIMPLEX,
106
- 0.7,
107
- (0,255,0),
108
- 2)
109
 
110
- detected_info.append(
111
- f"Plate: {plate_number}\nType: {vehicle_type}\n{benefit}"
112
- )
113
 
114
- if len(detected_info) == 0:
115
- summary = "No number plates detected."
116
- else:
117
- summary = "\n\n".join(detected_info)
 
118
 
119
- img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
120
 
121
- return img, summary
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
- ############################################################
125
- # Gradio UI
126
- ############################################################
 
127
 
128
- with gr.Blocks() as demo:
 
 
 
129
 
130
- gr.Markdown("## 🚦 Smart Traffic CCTV Number Plate Detection System")
 
131
 
132
- image_input = gr.Image(type="pil", label="Upload CCTV Image")
133
- detect_btn = gr.Button("Detect Plates", size="sm")
 
 
 
134
 
135
- output_image = gr.Image(label="Detection Output")
136
- output_text = gr.Textbox(label="Detection Summary")
 
 
 
137
 
138
- detect_btn.click(
139
- fn=detect_number_plates,
140
- inputs=image_input,
141
- outputs=[output_image, output_text]
142
  )
143
 
144
  demo.launch(theme=gr.themes.Soft())
 
1
  import gradio as gr
2
+ import matplotlib.pyplot as plt
3
+ import pandas as pd
4
+ import os
5
+ import random
6
+ from PIL import ImageDraw
7
+
8
+ # ===============================
9
+ # GLOBAL VARIABLES
10
+ # ===============================
11
+ total_vehicles = 0
12
+ ev_count = 0
13
+ total_co2_saved = 0
14
+
15
+ DISTANCE_KM = 10
16
+ CO2_PER_KM_PETROL = 0.150
17
+ CO2_SAVED_PER_EV = DISTANCE_KM * CO2_PER_KM_PETROL
18
+
19
+ FEEDBACK_FILE = "feedback.csv"
20
+
21
+ if not os.path.exists(FEEDBACK_FILE):
22
+ pd.DataFrame(columns=["Predicted_Label", "Feedback"]).to_csv(FEEDBACK_FILE, index=False)
23
+
24
+ # ===============================
25
+ # SIMULATED NUMBER PLATE COLOUR DETECTION
26
+ # Replace with real color detection later
27
+ # ===============================
28
+ def detect_plate_colour():
29
+ def classify_plate_color(plate_img):
30
+ try:
31
+ img = np.array(plate_img)
32
+ img = cv2.GaussianBlur(img, (5,5), 0)
33
+ hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
34
+
35
+ green_mask = cv2.inRange(hsv, (35, 40, 40), (85, 255, 255))
36
+ yellow_mask = cv2.inRange(hsv, (15, 50, 50), (35, 255, 255))
37
+ white_mask = cv2.inRange(hsv, (0, 0, 200), (180, 40, 255))
38
+
39
+ green = np.sum(green_mask)
40
+ yellow = np.sum(yellow_mask)
41
+ white = np.sum(white_mask)
42
+
43
+ if green > yellow and green > white:
44
+ return "Electric Vehicle (Green Plate)"
45
+ elif yellow > green and yellow > white:
46
+ return "Commercial Vehicle (Yellow Plate)"
47
+ elif white > green and white > yellow:
48
+ return "Private Vehicle (White Plate)"
49
+ else:
50
+ return "Unknown Classification"
51
+
52
+ except:
53
+ return "Unknown Classification"
54
+
55
+
56
+ def get_vehicle_type_from_colour(colour):
57
+ mapping = {
58
+ "White": "Private Vehicle",
59
+ "Yellow": "Commercial Vehicle",
60
+ "Green": "Electric Vehicle",
61
+ "Black": "Rental Vehicle"
62
  }
63
+ return mapping.get(colour, "Unknown")
64
+
65
+ # ===============================
66
+ # DASHBOARD
67
+ # ===============================
68
+ def generate_dashboard():
69
+ global total_vehicles, ev_count
70
+ non_ev = total_vehicles - ev_count
71
+
72
+ fig, ax = plt.subplots()
73
+ ax.bar(["EV", "Non-EV"], [ev_count, non_ev])
74
+ ax.set_title("Vehicle Distribution")
75
+ ax.set_ylabel("Count")
76
+ return fig
77
+
78
+ # ===============================
79
+ # EVALUATION SUMMARY
80
+ # ===============================
81
+ def get_evaluation_summary():
82
+ df = pd.read_csv(FEEDBACK_FILE)
83
+ total = len(df)
84
+ correct = len(df[df["Feedback"] == "Correct"])
85
+ incorrect = len(df[df["Feedback"] == "Incorrect"])
86
+
87
+ if total == 0:
88
+ return "Evaluation Summary:\nNo feedback yet."
89
+
90
+ precision = correct / total
91
+
92
+ return f"""Evaluation Summary
93
+ Total: {total}
94
+ Correct: {correct}
95
+ Incorrect: {incorrect}
96
+ Accuracy: {precision:.2f}
97
+ """
98
+
99
+ # ===============================
100
+ # DETECTION FUNCTION
101
+ # ===============================
102
+ def detect_image(image):
103
+
104
+ global total_vehicles, ev_count, total_co2_saved
105
 
106
  if image is None:
107
+ return None, "Upload image first.", "", "", "", "", "", ""
108
+
109
+ plate_colour = detect_plate_colour()
110
+ vehicle_type = get_vehicle_type_from_colour(plate_colour)
111
+ plate_number = "KA01AB1234"
112
+
113
+ total_vehicles += 1
114
+ co2_saved_this = 0
115
+
116
+ if vehicle_type == "Electric Vehicle":
117
+ ev_count += 1
118
+ co2_saved_this = CO2_SAVED_PER_EV
119
+ total_co2_saved += co2_saved_this
120
+
121
+ ev_percent = (ev_count / total_vehicles) * 100
122
+
123
+ # Draw boxes
124
+ img = image.copy()
125
+ draw = ImageDraw.Draw(img)
126
+ w, h = img.size
127
+
128
+ vehicle_box = [w*0.1, h*0.2, w*0.9, h*0.8]
129
+ plate_box = [w*0.4, h*0.6, w*0.7, h*0.75]
130
+
131
+ draw.rectangle(vehicle_box, outline="red", width=4)
132
+ draw.text((vehicle_box[0], vehicle_box[1]-20),
133
+ f"{vehicle_type}", fill="red")
134
+
135
+ draw.rectangle(plate_box, outline="green", width=4)
136
+ draw.text((plate_box[0], plate_box[1]-20),
137
+ f"{plate_number} ({plate_colour})", fill="green")
138
+
139
+ fig, ax = plt.subplots()
140
+ ax.imshow(img)
141
+ ax.axis("off")
142
+
143
+ result_text = f"""
144
+ Vehicle Type: {vehicle_type}
145
+ Plate Colour: {plate_colour}
146
+ Plate Number: {plate_number}
147
+ COβ‚‚ Saved: {co2_saved_this:.2f} kg
148
+ """
149
+
150
+ total_card = f"### 🚘 Total: {total_vehicles}"
151
+ ev_card = f"### ⚑ EV: {ev_count}"
152
+ percent_card = f"### πŸ“Š EV Rate: {ev_percent:.2f}%"
153
+ co2_card = f"### 🌱 COβ‚‚ Saved: {total_co2_saved:.2f} kg"
154
+
155
+ dashboard_fig = generate_dashboard()
156
+
157
+ summary = get_evaluation_summary()
158
+
159
+ return fig, result_text, total_card, ev_card, percent_card, co2_card, dashboard_fig, vehicle_type, summary
160
+
161
+ # ===============================
162
+ # FEEDBACK SAVE
163
+ # ===============================
164
+ def save_feedback(predicted_label, feedback):
165
+ df = pd.read_csv(FEEDBACK_FILE)
166
+ df = pd.concat([df, pd.DataFrame(
167
+ [{"Predicted_Label": predicted_label, "Feedback": feedback}]
168
+ )], ignore_index=True)
169
+ df.to_csv(FEEDBACK_FILE, index=False)
170
+ return "Saved!", get_evaluation_summary()
171
+
172
+ # ===============================
173
+ # RESET DATABASE
174
+ # ===============================
175
+ def reset_database():
176
+ pd.DataFrame(columns=["Predicted_Label", "Feedback"]).to_csv(FEEDBACK_FILE, index=False)
177
+ return "Database Reset!", "Evaluation Summary:\nNo feedback yet."
178
+
179
+ # ===============================
180
+ # UI
181
+ # ===============================
182
+ with gr.Blocks() as demo:
183
 
184
+ gr.Markdown("## 🚦 Smart Vehicle Detection Based on Number Plate Colour")
 
 
 
185
 
186
+ with gr.Row():
187
+ img_input = gr.Image(type="pil", label="Upload Vehicle Image")
188
+ img_output = gr.Plot()
189
 
190
+ detect_btn = gr.Button("Detect", size="sm")
 
 
 
 
 
 
191
 
192
+ result_box = gr.Textbox(label="Detection Result", lines=5)
 
 
193
 
194
+ with gr.Row():
195
+ total_card = gr.Markdown("### 🚘 Total: 0")
196
+ ev_card = gr.Markdown("### ⚑ EV: 0")
197
+ percent_card = gr.Markdown("### πŸ“Š EV Rate: 0%")
198
+ co2_card = gr.Markdown("### 🌱 COβ‚‚ Saved: 0 kg")
199
 
200
+ dashboard_plot = gr.Plot()
201
 
202
+ predicted_label_state = gr.State()
203
 
204
+ detect_btn.click(
205
+ fn=detect_image,
206
+ inputs=[img_input],
207
+ outputs=[
208
+ img_output,
209
+ result_box,
210
+ total_card,
211
+ ev_card,
212
+ percent_card,
213
+ co2_card,
214
+ dashboard_plot,
215
+ predicted_label_state,
216
+ gr.Markdown() # evaluation summary placeholder
217
+ ]
218
+ )
219
 
220
+ # -------------------------
221
+ # FEEDBACK + EVALUATION ROW
222
+ # -------------------------
223
+ with gr.Row():
224
 
225
+ with gr.Column(scale=1):
226
+ correct_btn = gr.Button("βœ”", size="sm")
227
+ incorrect_btn = gr.Button("✘", size="sm")
228
+ feedback_status = gr.Textbox(label="Feedback", lines=1)
229
 
230
+ with gr.Column(scale=1):
231
+ evaluation_summary = gr.Textbox(label="Evaluation Summary", lines=6)
232
 
233
+ correct_btn.click(
234
+ fn=save_feedback,
235
+ inputs=[predicted_label_state, gr.State("Correct")],
236
+ outputs=[feedback_status, evaluation_summary]
237
+ )
238
 
239
+ incorrect_btn.click(
240
+ fn=save_feedback,
241
+ inputs=[predicted_label_state, gr.State("Incorrect")],
242
+ outputs=[feedback_status, evaluation_summary]
243
+ )
244
 
245
+ reset_btn = gr.Button("Reset Database", size="sm")
246
+ reset_btn.click(
247
+ fn=reset_database,
248
+ outputs=[feedback_status, evaluation_summary]
249
  )
250
 
251
  demo.launch(theme=gr.themes.Soft())