File size: 8,334 Bytes
e1296a1 5ee84b0 412d849 e1296a1 66f7af6 e1296a1 5ee84b0 e1296a1 412d849 142be36 412d849 e1296a1 412d849 142be36 412d849 466386a 412d849 466386a 412d849 5ee84b0 466386a 142be36 466386a 5ee84b0 466386a 412d849 466386a 142be36 e1296a1 fd69e88 e1296a1 1b473cd 66f7af6 1b473cd ba3c040 1b473cd 12e5ff9 1b473cd d0cdff3 1b473cd 66f7af6 d0cdff3 7023974 d0cdff3 66f7af6 d0cdff3 66f7af6 12e5ff9 66f7af6 d0cdff3 66f7af6 d0cdff3 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 66f7af6 0e06770 66f7af6 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 0e06770 142be36 abe7371 623b383 5b6742c 0e06770 5b6742c 142be36 1b473cd 0e06770 142be36 ad163d7 47511b2 142be36 47511b2 1b473cd 47511b2 1b473cd 142be36 47511b2 142be36 47511b2 142be36 47511b2 8129506 142be36 469bbe2 6a5b6f3 469bbe2 66f7af6 469bbe2 66f7af6 352d599 469bbe2 66f7af6 e9fba3e | 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 | # Author Sarvamangala Kokatanur
# Import libraries
import gradio as gr
import torch
import numpy as np
import cv2
import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from PIL import Image, ImageDraw
from transformers import (
YolosImageProcessor,
YolosForObjectDetection
)
# Load model
processor = YolosImageProcessor.from_pretrained(
"nickmuchi/yolos-small-finetuned-license-plate-detection"
)
model = YolosForObjectDetection.from_pretrained(
"nickmuchi/yolos-small-finetuned-license-plate-detection"
)
model.eval()
# ---------------- DATABASE ----------------
conn = sqlite3.connect(
"vehicles.db",
check_same_thread=False
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS vehicles(
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
license_plate TEXT,
vehicle_status TEXT,
discount INTEGER
)
""")
conn.commit()
# -------- Plate Color Classifier -------- #
def classify_plate_color(plate_img):
img = np.array(plate_img)
# Convert RGB → HSV
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
h, w = hsv.shape[:2]
# Only inspect the left 20% of the plate
left = hsv[:, :int(w*0.2)]
# Green mask
green = cv2.inRange(
left,
(35, 40, 40),
(90, 255, 255)
)
green_ratio = np.count_nonzero(green) / green.size
# If more than 15% of the left strip is green,
# classify as EV
if green_ratio > 0.15:
return "EV"
return "Non-EV"
# Avoid duplicate vehicle details to the dashboard
def is_duplicate_vehicle(plate_number):
cursor.execute("""
SELECT timestamp
FROM vehicles
WHERE license_plate=?
ORDER BY id DESC
LIMIT 1
""",(plate_number,))
row = cursor.fetchone()
if row is None:
return False
last_time = datetime.strptime(
row[0],
"%Y-%m-%d %H:%M:%S"
)
if datetime.now() - last_time < timedelta(minutes=5):
return True
return False
# to save vehicle details in the database
def save_vehicle(plate,status):
if status=="EV":
discount=50
else:
discount=0
if is_duplicate_vehicle(plate):
return "Duplicate"
current_time=datetime.now().strftime(
"%Y-%m-%d %H:%M:%S"
)
cursor.execute("""
INSERT INTO vehicles(
timestamp,
license_plate,
vehicle_status,
discount
)
VALUES(?,?,?,?)
""",
(
current_time,
plate,
status,
discount
))
conn.commit()
return "Saved"
# --------get_dashboard function ------#
def get_dashboard():
df = pd.read_sql(
"SELECT * FROM vehicles",
conn
)
fig, axs = plt.subplots(2, 2, figsize=(8, 6))
if df.empty:
for ax in axs.flatten():
ax.text(
0.5,
0.5,
"No Data Available",
ha="center",
va="center",
fontsize=10
)
ax.axis("off")
plt.tight_layout()
return fig
status_counts = df["vehicle_status"].value_counts()
axs[0,0].bar(
status_counts.index,
status_counts.values
)
axs[0,0].set_title("EV vs Non-EV")
if status_counts.empty:
plt.tight_layout()
return fig
axs[0,1].pie(
status_counts.values,
labels=status_counts.index,
autopct="%1.1f%%"
)
axs[0,1].set_title("Vehicle Distribution")
total_discount = df["discount"].sum()
axs[1,0].bar(
["Discount"],
[total_discount]
)
axs[1,0].set_title("Total Discount")
axs[1,1].axis("off")
report = (
f"Today's Report\n\n"
f"Total Vehicles : {len(df)}\n\n"
f"EV : {len(df[df.vehicle_status=='EV'])}\n\n"
f"Non-EV : {len(df[df.vehicle_status=='Non-EV'])}\n\n"
f"Discount Given : ₹{total_discount}"
)
axs[1,1].text(
0,
1,
report,
fontsize=10,
va="top"
)
plt.tight_layout()
plt.close(fig)
return fig
# -------- Main Pipeline -------- #
def process_image(img):
if img is None:
return (
None,
"Please upload an image.",
"0",
"0",
"₹0",
get_dashboard()
)
image = Image.fromarray(img)
inputs = processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
target_sizes = torch.tensor([[image.size[1], image.size[0]]])
results = processor.post_process_object_detection(
outputs,
threshold=0.3,
target_sizes=target_sizes
)[0]
draw = ImageDraw.Draw(image)
ev_count = 0
non_ev_count = 0
discount_total = 0
output_text = ""
# No detection
if len(results["boxes"]) == 0:
return (
image,
"No license plate detected.",
"0",
"0",
"₹0",
get_dashboard()
)
# Process each detected plate
for i, box in enumerate(results["boxes"]):
x1, y1, x2, y2 = map(int, box.tolist())
plate = image.crop((x1, y1, x2, y2))
status = classify_plate_color(plate)
# Temporary plate number
# Replace with OCR later
plate_number = f"Vehicle_{datetime.now().strftime('%H%M%S%f')}_{i}"
saved = save_vehicle(
plate_number,
status
)
# Skip duplicate entries
if saved == "Duplicate":
continue
if status == "EV":
ev_count += 1
discount = 50
discount_total += discount
color = "green"
label = f"{plate_number}\nEV | ₹{discount}"
else:
non_ev_count += 1
discount = 0
color = "red"
label = f"{plate_number}\nNon-EV"
# Draw bounding box
draw.rectangle(
[x1, y1, x2, y2],
outline=color,
width=3
)
# Draw label
draw.text(
(x1, max(0, y1 - 30)),
label,
fill=color
)
output_text += (
f"Vehicle {i+1}\n"
f"Plate : {plate_number}\n"
f"Status : {status}\n"
f"Discount : ₹{discount}\n\n"
)
conn.commit()
dashboard = get_dashboard()
return (
image,
output_text,
str(ev_count),
str(non_ev_count),
f"₹{discount_total}",
dashboard
)
# -------- Gradio UI -------- #
css = """
textarea {
white-space: pre-wrap !important;
word-break: break-word !important;
overflow-wrap: break-word !important;
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("Smart Traffic & EV Analytics System")
gr.Markdown(
"Detects license plates, classifies vehicles, "
"calculates EV discounts and displays analytics."
)
# Images
with gr.Row():
input_img = gr.Image(
type="numpy",
sources=["upload", "webcam"],
label="Input Image"
)
output_img = gr.Image(
label="Detected Plate"
)
# ---------------- Button ----------------
btn = gr.Button("Scan Vehicle")
# ---------------- Detection Summary ----------------
with gr.Row():
summary_box = gr.Textbox(
label="Detection Summary",
lines=8
)
# ---------------- Statistics ----------------
with gr.Row():
ev_box = gr.Textbox(
label="EV Vehicles"
)
non_ev_box = gr.Textbox(
label="Non-EV Vehicles"
)
discount_box = gr.Textbox(
label="Total Discount"
)
# ---------------- Dashboard ----------------
dashboard = gr.Plot(
label="Today's Dashboard"
)
btn.click(
fn=process_image,
inputs=input_img,
outputs=[
output_img,
summary_box,
ev_box,
non_ev_box,
discount_box,
dashboard
]
)
if __name__ == "__main__":
demo.queue()
demo.launch(
ssr_mode=False
)
|