MediumBuilding an Automated Traffic Violation Logger: From Concept to Code | by SUPRIYA | Medium
Sitemap

Building an Automated Traffic Violation Logger: From Concept to Code

3 min readMay 2, 2026

--

Introduction

In an increasingly urbanized world, monitoring road safety is a monumental task. Manual surveillance is prone to human error and fatigue. To address this, I developed TrafficViolationLogger, an automated system designed to detect, log, and store traffic infractions in real-time.

The Problem

Traditional traffic monitoring often requires constant human oversight. My goal was to create a pipeline that could:

  1. Identify vehicles in a video stream.

2. Detect specific violations (like [Speeding / Red Light Jumping / Illegal Parking]).

Get SUPRIYA’s stories in your inbox

Join Medium for free to get updates from this writer.

3. Log the data into a structured format for further analysis.

The Tech Stack

To build this project, I utilized a modern stack focused on web-based management and automated data handling:

  • Backend Framework: Flask (Python) — Used to handle server-side logic, routing, and rendering the user interface.
  • Database: SQLite — A lightweight, disk-based database used to store vehicle violation history and record logs efficiently.
  • Data Manipulation: Pandas — Leveraged for structured data processing and managing violation logs.
  • Frontend & UI: HTML5 & CSS3 — Crafted a clean, responsive interface to display violation records and management tools.
  • Feature Integration: QR Code API / Libraries — Integrated to automatically generate payment QR codes for each logged violation, streamlining the fine-collection process.
  • Web Server: Werkzeug — Utilized as the underlying WSGI web application library.
Press enter or click to view image in full size
Photo by Erik Mclean on Unsplash

How it Works (The Workflow)

The system operates in three distinct phases:

  1. Detection Phase: The script initializes the camera or video file and applies a [mention model name] to track moving objects.
  2. Logic Phase: It checks the object’s coordinates against defined “violation zones.” If a vehicle enters a restricted area or exceeds a pixel-per-second threshold, a flag is raised.
  3. Logging Phase: Once a violation is confirmed, the system captures a timestamp, the type of violation, and an image snippet, saving them to the logs/ directory.

Core Script Highlight

Note to User: Create a GitHub Gist for your main script and paste the link here. If you want a placeholder, use this:

import sqlite3
import qrcode
import io
import base64
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)


def get_db_connection():
conn = sqlite3.connect('traffic_violations.db')
conn.row_factory = sqlite3.Row
return conn


@app.route('/')
def index():
search_query = request.args.get('search')
conn = get_db_connection()
if search_query:
violations = conn.execute("SELECT * FROM violation WHERE vehicle LIKE ?",
('%' + search_query + '%',)).fetchall()
else:
violations = conn.execute('SELECT * FROM violation').fetchall()
conn.close()
return render_template('index.html', violations=violations)


@app.route('/add', methods=['GET', 'POST'])
def add_violation():
if request.method == 'POST':
vehicle = request.form['vehicle']
vtype = request.form['vtype']
location = request.form['location']
fine = request.form['fine']

conn = get_db_connection()
conn.execute(
"INSERT INTO violation (vehicle, vtype, location, fine, status, issued_on) VALUES (?, ?, ?, ?, 'Unpaid', DATE('now'))",
(vehicle, vtype, location, fine))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('add.html')


@app.route('/view_challan/<int:id>')
def view_challan(id):
conn = get_db_connection()
violation = conn.execute('SELECT * FROM violation WHERE id = ?', (id,)).fetchone()
conn.close()

# Generate QR Code dynamically
qr_data = f"Vehicle: {violation['vehicle']} | Fine: {violation['fine']} | Status: {violation['status']}"
qr = qrcode.make(qr_data)
buf = io.BytesIO()
qr.save(buf)
qr_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')

return render_template('challan.html', violation=violation, qr_code=qr_b64)


@app.route('/pay_challan/<int:id>')
def pay_challan(id):
conn = get_db_connection()
conn.execute("UPDATE violation SET status = 'Paid', paid_on = DATE('now') WHERE id = ?", (id,))
conn.commit()
conn.close()
return redirect(url_for('view_challan', id=id))


if __name__ == '__main__':
app.run(debug=True,port=8080)

Challenges I Overcame

The biggest hurdle was [e.g., handling shadows or overlapping vehicles]. Initially, the system would double-count cars. I solved this by implementing a Centroid Tracking algorithm, which assigns a unique ID to each detected object, ensuring a violation is only logged once per vehicle.

Future Improvements

While the current version of TrafficViolationLogger is functional, I plan to:

  • Integrate Automatic Number Plate Recognition (ANPR).
  • Deploy the model using Docker for easier cloud scaling.
  • Add a web dashboard using Streamlit.

Conclusion

Building this project allowed me to dive deep into the intersection of AI and public safety. You can find the full source code, installation instructions, and sample datasets on my GitHub.

View the Project on GitHub: https://github.com/dreamer-1428/TrafficViolationLogger

--

--

SUPRIYA
SUPRIYA

Written by SUPRIYA

AI & Data Science student @ GCT | UPSC Aspirant | Focused on the intersection of Tech, Governance & Defense | Dedicated to National Security & AI Innovation