initial commit

This commit is contained in:
Yaay Nands 2025-05-01 17:59:14 +00:00
commit fe515d61ba
No known key found for this signature in database
GPG key ID: FEB9C1E69AAF6FA9
21 changed files with 846 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
videos/*
data/*

201
LICENSE Normal file
View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

13
README.md Normal file
View file

@ -0,0 +1,13 @@
# Number plate recognition system
## Install system dependencies:
* -- `sudo apt-get install tesseract-ocr-all`
* -- `mkdir db`
Number Plate recognition, also called License Plate realization or recognition using image processing methods is a potential research area in smart cities and the Internet of Things. An exponential increase in the number of vehicles necessitates the use of automated systems to maintain vehicle information for various purposes.
![ANPR](ANPR.jpg)
## Implementation:
In the proposed algorithm an efficient method for recognition of Indian vehicle number plates has been devised. We are able to deal with noisy, low illuminated, cross angled, non-standard font number plates. This work employs several image processing techniques such as, morphological transformation, Gaussian smoothing, Gaussian thresholding and Sobel edge detection method in the pre-processing stage, afterwhich number plate segmentation, contours are applied by border following and contours are filtered based on character dimensions and spatial localization. Finally we apply Optical Character Recognition (OCR) to recognize the extracted characters. The detected texts are stored in the database, further which they are sorted and made available for searching.
This project will work efficiently in recognizing owner's vehicle in small Institutions/Housing societies/Apartments. We can further modify the code to use it in other areas where ANPR is necessary.

260
anpr_main.py Normal file
View file

@ -0,0 +1,260 @@
# -*- coding: utf-8 -*-
# -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.#
#* File Name : anpr_yolo_v8.py
#* Purpose :
#* Creation Date : 21-04-2025
#* Last Modified : Thu 01 May 2025 05:48:26 PM UTC
#* Created By : Yaay Nands
#_._._._._._._._._._._._._._._._._._._._._.#
import glob
import logging
import os
import pprint as pp
import signal
import time
import traceback
# Async imports
import asyncio
import aiosqlite
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor
import functools
import aiofiles
from aiohttp import ClientSession, FormData, ConnectionTimeoutError, BasicAuth
from lib import anpr as anprm
from lib.consts import (
DB_RECORDINGS, VIDEO_OUT_FULL, VIDEO_OUT_ANAL, MODEL_NAME, RTSP_URL,
CONTOUR_MOTION_THRESHOLD, MAX_CLIP_TIME, MIN_TIME, CLASS_LABELS, CONFIG_JSON, AUTH_USER, AUTH_PASSWORD,
STATIONARY_THRESHOLD, FAST_LEARNING_RATE, GLOBAL_LEARNING_RATE, DIFF_THRESHOLD, MOTION_AREA_THRESHOLD
)
BASE_PATH = '.'
LOCATION_ID = 1
HAS_CONFIG = False
if os.path.exists(CONFIG_JSON):
with open(CONFIG_JSON, "r") as f:
config = json.load(f)
HAS_CONFIG = True
else:
config = {}
SQL = {
'INSERT_NUMBERS':
'INSERT INTO numberplates (model, filename, ts, ) VALUES (? , ?, ?)',
'UPDATE_NUMBERS':
'UPDATE numberplates set anal_complete=?, numberplates=? \
WHERE model=? AND filename=? AND ts=?',
'SELECT_UNPROCESSED':
'SELECT model, filename, ts FROM numberplates WHERE anal_complete=0;',
}
MODEL_NAME="YOLOv8"
daily_log_ts = time.strftime("%Y-%m-%d-%H:%M")
logging.basicConfig(
filename= f"logs/main-{daily_log_ts}.log",
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
)
logger = logging.getLogger("anpr_async_loop")
async def anpr_thread_loop():
async with aiosqlite.connect(DB_RECORDINGS) as db:
logger.debug(db.__str__())
db.row_factory = aiosqlite.Row
signal_received = asyncio.Event()
loop = asyncio.get_running_loop()
for signame in {'SIGINT', 'SIGTERM'}:
loop.add_signal_handler(getattr(signal, signame), lambda s=signame: signal_received.set())
tasks = [
#asyncio.create_task(motion_capture_and_record(db, signal_received)),
asyncio.create_task(capture_number_plate(db, signal_received)),
]
#if HAS_CONFIG and config['do_anal']:
# tasks.append(asyncio.create_task(do_analysis(db, signal_received)))
try:
await asyncio.gather(*tasks)
except asyncio.CancelledError:
logger.error("Closing loop anpr_monitor_loop")
#break
except Exception as e:
logger.critical(f"Error in anpr_monitor loop:")
err_type = type(e).__name__
line_no = e.__traceback__.tb_lineno
logger.critical(f"traceback:{traceback.format_tb(e.__traceback__)} ")
logger.critical(f"Error {err_type} occurred on line: {line_no}")
finally:
logger.info("finally shutting down")
for task in tasks:
task.cancel()
await db.commit()
await db.close()
async def motion_capture_and_record(db, signal_received):
logger.debug("motion_capture_and_record task running")
loop = asyncio.get_running_loop()
# logger.debug(f"CONTOUR_MOTION_THRESHOLD: {CONTOUR_MOTION_THRESHOLD}")
with ThreadPoolExecutor() as pool:
previous_frame = None
motion_detected = False
output_file = None
start_time = 0
recording = False
recording_process = None
# startrecord_stderr = ''
# startrecord_stdout = ''
loop_in_pool = functools.partial(loop.run_in_executor, pool)
cap = await loop_in_pool(lambda: cv2.VideoCapture(RTSP_URL))
cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
if not cap.isOpened():
logger.critical("Error: Could not open RTSP stream.")
return
ret, frame = cap.read()
if not ret:
logger.critical("Error: Unable to capture video.")
cap.release()
sys.exit(-1)
# Convert the first frame to grayscale and blur to reduce noise
gray_init = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_init = cv2.GaussianBlur(gray_init, (21, 21), 0)
# Initialize the background model as a floating point image for blending
background = gray_init.astype("float")
# Create an image to count how many consecutive frames a pixel is stationary
stationary_counter = np.zeros_like(gray_init, dtype=np.uint8)
while not signal_received.is_set():
try:
try:
ret, frame = await loop_in_pool(lambda: cap.read())
except Exception as e:
logger.debug(f"Error capturing frame: {e}")
continue
if not ret or not is_valid_frame(frame):
logger.debug("Failed to capture from IP camera")
break
if not cap.isOpened():
logger.debug("RTSP stream disconnected. Reconnecting")
cap.release()
cap = await loop_in_pool(lambda: cv2.VideoCapture(RTSP_URL))
cap.set(cv2.CAP_PROP_BUFFERSIZE, 2)
# Preprocess: convert to grayscale and apply Gaussian blur
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray_blurred = cv2.GaussianBlur(gray, (21, 21), 0)
# Compute absolute difference between the current background and the new frame
diff = cv2.absdiff(cv2.convertScaleAbs(background), gray_blurred)
_, motion_mask = cv2.threshold(diff, DIFF_THRESHOLD, 255, cv2.THRESH_BINARY)
# Invert motion mask to get stationary areas (low difference)
stationary_mask = cv2.bitwise_not(motion_mask)
# Update the stationary counter: add 1 where stationary, reset where motion is detected
stationary_counter = cv2.add(stationary_counter, (stationary_mask // 255))
stationary_counter[motion_mask == 255] = 0
# Determine where pixels have been stationary long enough
update_mask = (stationary_counter >= STATIONARY_THRESHOLD).astype(np.float32)
# Create an effective learning rate for each pixel:
# Pixels meeting the stationary criteria use fast_learning_rate,
# otherwise, they use the global (slow) learning rate.
effective_learning_rate = GLOBAL_LEARNING_RATE + update_mask * (FAST_LEARNING_RATE - GLOBAL_LEARNING_RATE)
# Update the background model for all pixels using the effective learning rate
background = (1 - effective_learning_rate) * background + effective_learning_rate * gray_blurred
motion_detected = False
# Motion detection: if enough pixels are marked as moving, declare motion
motion_pixels = cv2.countNonZero(motion_mask)
if motion_pixels > MOTION_AREA_THRESHOLD:
motion_detected = True
delta = time.time() - start_time
if motion_detected and not recording:
start_time = time.time()
logger.debug(f"Motion detected! Starting recording... {start_time}")
timestamp = time.strftime("%Y%m%d-%H%M%S")
output_file = f"motion_{timestamp}.mp4"
recording_process = await ffmpeg_start_recording(os.path.join(VIDEO_OUT_FULL, output_file))
recording = True
# If no motion is detected and we're recording, stop recording
elif ((not motion_detected and recording and delta > MIN_TIME) or
(motion_detected and recording and delta > MAX_CLIP_TIME)):
logger.debug("No motion detected or MAX_CLIP_TIME exceeded. Stopping recording...")
if recording_process:
await ffmpeg_stop_recording(recording_process)
await asyncio.sleep(0.1)
# logger.debug(f"startrecord_stderr: {startrecord_stderr}")
# logger.debug(f"startrecord_stdout: {startrecord_stdout}")
# if startrecord_stderr:
# with open(f"logs/ffmpeg-{output_file}-err.log") as fe:
# fe.write(str(startrecord_stderr))
# if startrecord_stdout:
# with open(f"logs/ffmpeg-{output_file}-out.log") as fo:
# fo.write(str(startrecord_stdout))
cursor = await db.execute(SQL["INSERT_NUMBERS"], (MODEL_NAME, output_file, timestamp))
await cursor.fetchone()
logger.debug(f"inserted recording with id: {cursor.lastrowid}")
recording_process = None
recording = False
except asyncio.CancelledError:
logger.debug("Closing loop motion_capture_and_record")
await db.commit()
break
except Exception as e:
logger.critical(f"Error in produce_anal_file:")
err_type = type(e).__name__
line_no = e.__traceback__.tb_lineno
logger.critical(f"Error {err_type} occurred on line: {line_no}")
async def capture_number_plate(db, signal_received):
#loop = asyncio.get_running_loop()
logger.debug("capture_number_plate task running")
with ThreadPoolExecutor() as pool:
while not signal_received.is_set():
try:
cursor = await db.execute(SQL["SELECT_UNPROCESSED"])
res = await cursor.fetchall()
logger.debug("found unprocessed records: %i ", len(res))
for record in res:
#logger.debug("processing record: %s"%json.dumps(record))
plates = anprm.infer(filename)
cursor = await db.execute(SQL["UPDATE_NUMBERS"],
(True, 'NOMARS', record['model'],
record['filename'],
record['ts']))
res = await cursor.fetchone()
except asyncio.CancelledError:
logger.debug("Closing loop capture_number_plate")
#break
except Exception as e:
logger.critical(f"traceback:{traceback.format_tb(e.__traceback__)} ")
logger.critical(f"Error in capture_number_plate logic:")
err_type = type(e).__name__
line_no = e.__traceback__.tb_lineno
logger.critical(f"Error {err_type} occurred on line: {line_no}")
if __name__ == '__main__':
try:
asyncio.run(anpr_thread_loop(), debug=True)
except RuntimeError as e:
logger.debug(f"Error in asyncio.run(main()) loop: {str(e)}")
print("Error in asyncio.run(main()) loop: ", str(e))

BIN
db/numberplates.sqlite3 Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

127
lib/anpr.py Normal file
View file

@ -0,0 +1,127 @@
import glob
import os
import pytesseract
import re
import torch
import ultralytics
from ultralytics import YOLO
from PIL import Image
ultralytics.checks()
from xml.etree import ElementTree as ET
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
BASE_PATH = '..'
def convert_bbox_to_yolo(
size: tuple[float, float], box: tuple[float, float, float, float]
) -> tuple[float, float, float, float]:
"""Convert bounding box from absolute coordinates to relative coordinates.
:param size: Tuple of (width, height) of the image.
:param box: Tuple of (xmin, ymin, xmax, ymax) for the bounding box.
:return: Tuple of (x_center, y_center, width, height) in relative
coordinates.
"""
scale_width = 1.0 / size[0]
scale_height = 1.0 / size[1]
center_x = (box[0] + box[2]) / 2.0
center_y = (box[1] + box[3]) / 2.0
box_width = box[2] - box[0]
box_height = box[3] - box[1]
rel_center_x = center_x * scale_width
rel_center_y = center_y * scale_height
rel_width = box_width * scale_width
rel_height = box_height * scale_height
return (rel_center_x, rel_center_y, rel_width, rel_height)
def xml_to_txt(input_xml: str, output_txt: str, class_mapping: dict[str, int]):
"""Parse an XML file and write to a .txt file in YOLO format.
:param input_xml: Path to the input XML file.
:param output_txt: Path to the output .txt file.
:param class_mapping: Dictionary mapping class names to class.
"""
tree = ET.parse(input_xml)
root = tree.getroot()
width = int(root.find(".//size/width").text)
height = int(root.find(".//size/height").text)
with open(output_txt, "w", encoding="utf-8") as txt_file:
for obj in root.iter("object"):
cell_name = obj.find("name").text
cell_id = class_mapping.get(cell_name, -1)
if cell_id == -1:
continue
xmlbox = obj.find("bndbox")
box = (
float(xmlbox.find("xmin").text),
float(xmlbox.find("ymin").text),
float(xmlbox.find("xmax").text),
float(xmlbox.find("ymax").text),
)
bbox = convert_bbox_to_yolo((width, height), box)
txt_file.write(f"{cell_id} {' '.join([str(a) for a in bbox])}\n")
def download_kaggle_data():
import kagglehub
if not os.path.exists(f"{BASE_PATH}/data/indian-number-plates-dataset"):
# Download latest version
path = kagglehub.dataset_download("dataclusterlabs/indian-number-plates-dataset")
print("Path to dataset files:", path)
def convert_to_yolo_format(data_path):
import glob
files = glob.glob(data_path + '/*.xml')
print(len(files))
for xml_fil in files:
if not os.path.isdir(xml_fil):
txt_fil = xml_fil.split('.')[:-1]
txt_fil = '.'.join(txt_fil) + '.txt'
xml_to_txt(xml_fil, txt_fil, class_mapping = {'number_plate': '0'})
files = glob.glob(data_path + '/*.txt')
print(len(files))
def train_model():
from ultralytics.data.dataset import YOLODataset
dataset = YOLODataset(img_path=f"{BASE_PATH}/data/train/images", data={"names": {0: "person"}}, task="detect")
dataset.get_labels()
model = YOLO(f"{BASE_PATH}/models/yolov8n.pt")
results = model.train(data=f'{BASE_PATH}/data/data.yaml', epochs=50, imgsz=1728)
model.export(format='onnx', dynamic=True,
#path = "../models/yolov8n_anpr.onnx",
simplify=True, device=device)
def infer(filename):
model2 = YOLO(f"{BASE_PATH}/models/train25/best.pt")
test_result = model2.predict(source=filename)
#onnx_model = YOLO("../models/train25/best.onnx")
#model_2 = YOLO('/kaggle/input/weights/best(2).pt')
#testfiles = glob.glob('../data/TEST/*')
#import pdb; pdb.set_trace()
#test_result = model2.predict(source=testfiles[4])
number_plates = dict()
for i, res in enumerate(test_result):
res_img = res.plot()
plate_im = Image.fromarray(res_img)
np_text = pytesseract.image_to_string(plate_im, lang='eng')
plate = str("".join(re.split("[^a-zA-Z0-9]*", np_text)))
number_plates[i] = plate.upper()
return number_plates
#download_kaggle_data()
#data_path = '../data/train/labels'
#convert_to_yolo_format(data_path)
#data_path = '../data/TEST/labels'
#convert_to_yolo_format(data_path)
#train_model()

23
lib/consts.py Normal file
View file

@ -0,0 +1,23 @@
DB_RECORDINGS = "db/numberplates.sqlite3"
VIDEO_OUT_FULL = "videos/full/"
VIDEO_OUT_ANAL = "videos/analysis"
MODEL_NAME = "models/train25/best.pt"
RTSP_URL = "rtsp://admin:C4sinfra12@192.168.1.10:554/rtsp"
SCREEN_RESOLUTION = (1280, 720) # Resolution of the RTSP stream
BITRATE = 1000000 # Bitrate for video recording
CONTOUR_MOTION_THRESHOLD = 800 # Sensitivity for motion detection
MAX_CLIP_TIME = 20 # Maximum recording time in seconds
MIN_TIME = 10 # Minimum recording time in seconds
CLASS_LABELS = ["dumping", "not"]
CONFIG_JSON = "config.json"
AUTH_USER = 'c4suser'
AUTH_PASSWORD = 'c4sinfra!'
STATIONARY_THRESHOLD = 50 # Number of frames a pixel must remain stationary to be updated faster
FAST_LEARNING_RATE = 0.1 # Learning rate for pixels that have been stationary
GLOBAL_LEARNING_RATE = 0.01 # Slow, continuous update for all pixels
DIFF_THRESHOLD = 25 # Pixel intensity difference threshold for motion detection
MOTION_AREA_THRESHOLD = 5000 # Minimum number of changed pixels to declare motion

66
lib/ffmpeg.py Normal file
View file

@ -0,0 +1,66 @@
import asyncio
import signal
import os
from .consts import RTSP_URL, VIDEO_OUT_FULL, VIDEO_OUT_ANAL
async def ffmpeg_start_recording(file):
ffmpeg_args = [
"-rtsp_transport", "tcp",
"-timeout", "5000000",
"-i", RTSP_URL,
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-preset", "fast",
"-b:v", "1M",
"-f", "mp4",
"-an", file
]
process = await asyncio.create_subprocess_exec('ffmpeg', *ffmpeg_args,
stdout=asyncio.subprocess.DEVNULL,
stderr=asyncio.subprocess.DEVNULL
)
return process
async def ffmpeg_stop_recording(process):
# logger.debug("Inside ffmpeg_stop_recording")
if process:
# logger.debug(f"Sending SIGQUIT to recording_process: {process}")
process.send_signal(signal.SIGQUIT)
try:
await asyncio.wait_for(process.wait(), timeout=2)
except Exception as e:
# logger.debug(f"Got an exception while waiting for the process to finish: {e}")
process.kill()
await process.wait()
async def ffmpeg_create_anal_file(file, anal_file):
print("Inside ffmpeg_create_anal_file")
print(f"VIDEO_OUT_FULL: {VIDEO_OUT_FULL}, VIDEO_OUT_ANAL: {VIDEO_OUT_ANAL}, file:{file}, anal_file: {anal_file} ")
ffmpeg_args = [
"-y", "-i", os.path.join(VIDEO_OUT_FULL, file),
"-vf", "scale=456:256,setsar=1",
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-an", "-movflags", "faststart",
os.path.join(VIDEO_OUT_ANAL, anal_file)
]
# logger.debug(f"writing to: {os.path.join(VIDEO_OUT_ANAL, anal_file)}")
# logger.debug(f"calling ffmpeg with {' '.join(ffmpeg_args)}")
process = await asyncio.create_subprocess_exec('ffmpeg', *ffmpeg_args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# monitor_task = asyncio.create_task(monitor_process(process))
# monitor_task.add_done_callback(
# lambda task: asyncio.create_task(cb_completed(row_id, anal_file))
# )
stdout, stderr = await process.communicate()
return stdout, stderr
# logger.debug(f"Process: {process} ended with return code: {process.returncode}")
# if stderr:
# logger.debug("stderr:")
# logger.debug(stderr.decode())
# if stdout:
# logger.debug("stdout:")
# logger.debug(stdout.decode())

BIN
models/train23/best.pt Normal file

Binary file not shown.

BIN
models/train23/last.pt Normal file

Binary file not shown.

BIN
models/train25/best.onnx Normal file

Binary file not shown.

BIN
models/train25/best.pt Normal file

Binary file not shown.

BIN
models/train25/last.pt Normal file

Binary file not shown.

133
opencv_model.py Normal file
View file

@ -0,0 +1,133 @@
import sys
import glob
import os
import glob
import numpy as np
import cv2
from PIL import Image
import pytesseract
import re
def clean2_plate(plate):
gray_img = cv2.cvtColor(plate, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray_img, 110, 255, cv2.THRESH_BINARY)
#if cv2.waitKey(0) & 0xff == ord('q'):
# pass
num_contours,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if num_contours:
contour_area = [cv2.contourArea(c) for c in num_contours]
max_cntr_index = np.argmax(contour_area)
max_cnt = num_contours[max_cntr_index]
max_cntArea = contour_area[max_cntr_index]
x,y,w,h = cv2.boundingRect(max_cnt)
if not ratioCheck(max_cntArea,w,h):
return plate,None
final_img = thresh[y:y+h, x:x+w]
return final_img,[x,y,w,h]
else:
return plate,None
def ratioCheck(area, width, height):
ratio = float(width) / float(height)
if ratio < 1:
ratio = 1 / ratio
if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):
return False
return True
def isMaxWhite(plate):
avg = np.mean(plate)
if(avg>=115):
return True
else:
return False
def ratio_and_rotation(rect):
(x, y), (width, height), rect_angle = rect
if(width>height):
angle = -rect_angle
else:
angle = 90 + rect_angle
if angle>15:
return False
if height == 0 or width == 0:
return False
area = height*width
if not ratioCheck(area,width,height):
return False
else:
return True
#Detecting numberplate
def number_plate_detection(img):
img2 = cv2.GaussianBlur(img, (5,5), 0)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
img2 = cv2.Sobel(img2,cv2.CV_8U,1,0,ksize=3)
_,img2 = cv2.threshold(img2,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
element = cv2.getStructuringElement(shape=cv2.MORPH_RECT, ksize=(17, 3))
morph_img_threshold = img2.copy()
cv2.morphologyEx(src=img2, op=cv2.MORPH_CLOSE, kernel=element, dst=morph_img_threshold)
num_contours, hierarchy= cv2.findContours(morph_img_threshold,mode=cv2.RETR_EXTERNAL,method=cv2.CHAIN_APPROX_NONE)
cv2.drawContours(img2, num_contours, -1, (0,255,0), 1)
for i,cnt in enumerate(num_contours):
min_rect = cv2.minAreaRect(cnt)
if ratio_and_rotation(min_rect):
x,y,w,h = cv2.boundingRect(cnt)
plate_img = img[y:y+h,x:x+w]
if(isMaxWhite(plate_img)):
clean_plate, rect = clean2_plate(plate_img)
if rect:
fg=0
x1,y1,w1,h1 = rect
x,y,w,h = x+x1,y+y1,w1,h1
plate_im = Image.fromarray(clean_plate)
text = pytesseract.image_to_string(plate_im, lang='eng')
return text
print("HELLO!!")
print("Welcome to the Number Plate Detection System.\n")
array=[]
dir = os.path.dirname(__file__)
for img in glob.glob(dir+"/Images/*.jpeg") :
img=cv2.imread(img)
img2 = cv2.resize(img, (600, 600))
cv2.imshow("Image of car ",img2)
cv2.waitKey(1000)
cv2.destroyAllWindows()
number_plate=number_plate_detection(img)
res2 = str("".join(re.split("[^a-zA-Z0-9]*", number_plate)))
res2=res2.upper()
print(res2)
array.append(res2)
import pprint
pprint.pprint(array)
img = cv2.imread("./Search_Image/Car.jpeg")
number_plate=number_plate_detection(img)
import pdb; pdb.set_trace()
res2 = str("".join(re.split("[^a-zA-Z0-9]*", number_plate)))
print("The car number is:- ",res2)

5
requirements.txt Normal file
View file

@ -0,0 +1,5 @@
aiohttp
aiofiles
pytesseract
ultralytics

1
sql/count.sql Normal file
View file

@ -0,0 +1 @@
SELECT count(1) FROM recordings;

View file

@ -0,0 +1,13 @@
BEGIN;
CREATE TABLE numberplates(
model TEXT,
filename TEXT,
ts DATETIME DEFAULT (datetime('now', 'localtime')),
anal_complete BOOLEAN NOT NULL DEFAULT FALSE,
numberplates TEXT,
);
CREATE INDEX filename_idx ON numberplates (filename);
CREATE INDEX ts_idx ON numberplates (ts);
CREATE INDEX anal_complete_idx ON numberplates (anal_complete);
COMMIT;

1
sql/dropall.sql Normal file
View file

@ -0,0 +1 @@
DELETE FROM numberplates;

1
sql/selectall.sql Normal file
View file

@ -0,0 +1 @@
SELECT rowid, * FROM numberplates;