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t
|
| 8 |
+
from PIL import Image, ImageDraw
|
| 9 |
+
from transformers import YolosImageProcessor, YolosForObjectDetection
|
| 10 |
+
import easyocr
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
# -------------------- Database --------------------
|
| 14 |
+
conn = sqlite3.connect("vehicles.db", check_same_thread=False)
|
| 15 |
+
cursor = conn.cursor()
|
| 16 |
+
cursor.execute("""
|
| 17 |
+
CREATE TABLE IF NOT EXISTS vehicles (
|
| 18 |
+
plate TEXT,
|
| 19 |
+
type TEXT,
|
| 20 |
+
time TEXT
|
| 21 |
+
)
|
| 22 |
+
""")
|
| 23 |
+
conn.commit()
|
| 24 |
+
|
| 25 |
+
# -------------------- Models --------------------
|
| 26 |
+
processor = YolosImageProcessor.from_pretrained(
|
| 27 |
+
"nickmuchi/yolos-small-finetuned-license-plate-detection"
|
| 28 |
+
)
|
| 29 |
+
model = YolosForObjectDetection.from_pretrained(
|
| 30 |
+
"nickmuchi/yolos-small-finetuned-license-plate-detection"
|
| 31 |
+
)
|
| 32 |
+
model.eval()
|
| 33 |
+
|
| 34 |
+
reader = easyocr.Reader(['en'], gpu=False)
|
| 35 |
+
|
| 36 |
+
# -------------------- Plate Color Classifier --------------------
|
| 37 |
+
def classify_plate_color(plate_img):
|
| 38 |
+
img = np.array(plate_img)
|
| 39 |
+
hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
|
| 40 |
+
|
| 41 |
+
green = np.sum(cv2.inRange(hsv, (35, 40, 40), (85, 255, 255)))
|
| 42 |
+
yellow = np.sum(cv2.inRange(hsv, (15, 50, 50), (35, 255, 255)))
|
| 43 |
+
white = np.sum(cv2.inRange(hsv, (0, 0, 200), (180, 30, 255)))
|
| 44 |
+
|
| 45 |
+
if green > yellow and green > white:
|
| 46 |
+
return "EV"
|
| 47 |
+
elif yellow > green and yellow > white:
|
| 48 |
+
return "Commercial"
|
| 49 |
+
else:
|
| 50 |
+
return "Personal"
|
| 51 |
+
|
| 52 |
+
# -------------------- OCR --------------------
|
| 53 |
+
def read_plate(plate_img):
|
| 54 |
+
results = reader.readtext(np.array(plate_img))
|
| 55 |
+
if results:
|
| 56 |
+
return results[0][1]
|
| 57 |
+
return "UNKNOWN"
|
| 58 |
+
|
| 59 |
+
# -------------------- Dashboard --------------------
|
| 60 |
+
def get_dashboard():
|
| 61 |
+
df = pd.read_sql("SELECT * FROM vehicles", conn)
|
| 62 |
+
|
| 63 |
+
fig, ax = plt.subplots(figsize=(6, 4))
|
| 64 |
+
|
| 65 |
+
if len(df) == 0:
|
| 66 |
+
ax.text(0.5, 0.5, "No vehicles scanned yet",
|
| 67 |
+
ha="center", va="center", fontsize=14)
|
| 68 |
+
ax.axis("off")
|
| 69 |
+
return fig
|
| 70 |
+
|
| 71 |
+
counts = df["type"].value_counts()
|
| 72 |
+
counts.plot(kind="bar", ax=ax)
|
| 73 |
+
|
| 74 |
+
ax.set_title("Vehicle Classification Dashboard")
|
| 75 |
+
ax.set_xlabel("Vehicle Type")
|
| 76 |
+
ax.set_ylabel("Count")
|
| 77 |
+
ax.grid(axis="y")
|
| 78 |
+
|
| 79 |
+
return fig
|
| 80 |
+
|
| 81 |
+
# -------------------- Main Pipeline --------------------
|
| 82 |
+
def process_image(img):
|
| 83 |
+
image = Image.fromarray(img)
|
| 84 |
+
|
| 85 |
+
inputs = processor(images=image, return_tensors="pt")
|
| 86 |
+
with torch.no_grad():
|
| 87 |
+
outputs = model(**inputs)
|
| 88 |
+
|
| 89 |
+
results = processor.post_process_object_detection(
|
| 90 |
+
outputs,
|
| 91 |
+
threshold=0.3,
|
| 92 |
+
target_sizes=torch.tensor([[image.size[1], image.size[0]]])
|
| 93 |
+
)[0]
|
| 94 |
+
|
| 95 |
+
draw = ImageDraw.Draw(image)
|
| 96 |
+
|
| 97 |
+
if len(results["boxes"]) == 0:
|
| 98 |
+
return image, "No plate detected", "", get_dashboard()
|
| 99 |
+
|
| 100 |
+
x1, y1, x2, y2 = map(int, results["boxes"][0].tolist())
|
| 101 |
+
plate_img = image.crop((x1, y1, x2, y2))
|
| 102 |
+
|
| 103 |
+
plate_text = read_plate(plate_img)
|
| 104 |
+
vehicle_type = classify_plate_color(plate_img)
|
| 105 |
+
|
| 106 |
+
cursor.execute(
|
| 107 |
+
"INSERT INTO vehicles VALUES (?, ?, ?)",
|
| 108 |
+
(plate_text, vehicle_type, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
| 109 |
+
)
|
| 110 |
+
conn.commit()
|
| 111 |
+
|
| 112 |
+
draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
|
| 113 |
+
draw.text((x1, y1 - 12), f"{plate_text} | {vehicle_type}", fill="red")
|
| 114 |
+
|
| 115 |
+
return image, plate_text, vehicle_type, get_dashboard()
|
| 116 |
+
|
| 117 |
+
# -------------------- Gradio UI --------------------
|
| 118 |
+
with gr.Blocks() as demo:
|
| 119 |
+
gr.Markdown("## 🚦 Smart Traffic & EV Analytics System")
|
| 120 |
+
gr.Markdown(
|
| 121 |
+
"Detects license plates, reads number plate text, "
|
| 122 |
+
"classifies EV / Commercial / Personal vehicles, "
|
| 123 |
+
"and shows live analytics."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
with gr.Row():
|
| 127 |
+
input_img = gr.Image(type="numpy", sources=["upload", "webcam"])
|
| 128 |
+
output_img = gr.Image()
|
| 129 |
+
|
| 130 |
+
with gr.Row():
|
| 131 |
+
plate_box = gr.Textbox(label="Number Plate")
|
| 132 |
+
type_box = gr.Textbox(label="Vehicle Type")
|
| 133 |
+
|
| 134 |
+
dashboard = gr.Plot(label="Live Vehicle Dashboard")
|
| 135 |
+
|
| 136 |
+
btn = gr.Button("Scan Vehicle")
|
| 137 |
+
btn.click(
|
| 138 |
+
process_image,
|
| 139 |
+
input_img,
|
| 140 |
+
[output_img, plate_box, type_box, dashboard]
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
demo.launch()
|