This commit is contained in:
роман печеркин 2025-04-14 21:10:08 +07:00
commit 645e561ebf
53 changed files with 1370 additions and 0 deletions

7
.env Normal file
View File

@ -0,0 +1,7 @@
DB_NAME=dbname
DB_USER=username
DB_PASSWORD=urpassword
DB_HOST=localhost
DB_PORT=5432
RTSP_URL=C:/kpp/app/images/шлагбаум1.mkv # путь к камере (пока что только видео)

29
.gitignore vendored Normal file
View File

@ -0,0 +1,29 @@
.idea
.ipynb_checkpoints
.mypy_cache
.vscode
__pycache__
.pytest_cache
htmlcov
dist
site
.coverage*
coverage.xml
.netlify
test.db
log.txt
Pipfile.lock
env3.*
env
docs_build
site_build
venv
docs.zip
archive.zip
# vim temporary files
*~
.*.sw?
.cache
# macOS
.DS_Store

6
README.md Normal file
View File

@ -0,0 +1,6 @@
запуск программы осуществляется при помощи uvicorn
uvicorn main:app --host 0.0.0.0 --port 8000
endpoints :
http://hostname:8000/app/v1/stream

7
app/__init__.py Normal file
View File

@ -0,0 +1,7 @@
# from ultralytics import YOLO
# from .api import *
# import os
# from .services import *
# from services import *
# from api import *

0
app/api/__init__.py Normal file
View File

View File

@ -0,0 +1,137 @@
[
{
"Start Time": "2025-04-10T19:43:56.756258",
"End Time": "2025-04-10T19:44:16.830570",
"License Plate": [
"5691EX3"
]
},
{
"Start Time": "2025-04-10T19:44:16.830570",
"End Time": "2025-04-10T19:44:36.902341",
"License Plate": [
"5691EX3"
]
},
{
"Start Time": "2025-04-10T19:44:36.902341",
"End Time": "2025-04-10T19:44:56.978730",
"License Plate": [
"9121CX7",
"E9121CX7",
"\u76969121CX7"
]
},
{
"Start Time": "2025-04-10T19:54:15.838565",
"End Time": "2025-04-10T19:54:35.847936",
"License Plate": [
"56918X3",
"\u76965691EK3",
"\u76965591EX3",
"9",
"5691EX",
"\u76965691EX3",
"5691EX3",
"5691X3",
"691EX3",
"5591EX3",
"569EX3"
]
},
{
"Start Time": "2025-04-11T00:42:20.435220",
"End Time": "2025-04-11T00:42:40.481205",
"License Plate": [
"9",
"5591EX3",
"5691EX3",
"\u76965691EK3",
"691EX3",
"569EX3",
"\u76965591EX3",
"5691X3",
"56918X3",
"5691EX",
"\u76965691EX3"
]
},
{
"Start Time": "2025-04-11T00:47:58.727056",
"End Time": "2025-04-11T00:48:18.912928",
"License Plate": [
"5691EX",
"569EX3",
"\u76965691EX3",
"5691X3",
"5691EX3",
"5591EX3",
"56918X3",
"\u76965691EK3",
"\u76965591EX3",
"9",
"691EX3"
]
},
{
"Start Time": "2025-04-11T00:48:18.912928",
"End Time": "2025-04-11T00:48:39.154114",
"License Plate": [
"5691EX",
"\u4e2d",
"\u76965691EX3",
"5691EX3",
"5601EX3",
"9",
"5691EX1",
"\u6d595691EX3"
]
},
{
"Start Time": "2025-04-11T00:51:08.175327",
"End Time": "2025-04-11T00:51:28.214272",
"License Plate": [
"9",
"\u76965691EK3",
"5691X3",
"\u76965591EX3",
"56918X3",
"5691EX3",
"569EX3",
"5591EX3",
"5691EX",
"\u76965691EX3",
"691EX3"
]
},
{
"Start Time": "2025-04-11T00:51:28.214272",
"End Time": "2025-04-11T00:51:48.479129",
"License Plate": [
"9",
"5691EX1",
"5691EX3",
"5601EX3",
"\u6d595691EX3",
"\u4e2d",
"5691EX",
"\u76965691EX3"
]
},
{
"Start Time": "2025-04-11T00:51:48.479129",
"End Time": "2025-04-11T00:52:08.692791",
"License Plate": [
"\u8d635691EX3",
"\u76965691EX3",
"5691EX3"
]
},
{
"Start Time": "2025-04-11T00:52:08.692791",
"End Time": "2025-04-11T00:52:28.960917",
"License Plate": [
"5691EX3"
]
}
]

View File

@ -0,0 +1,7 @@
{
"Start Time": "2025-04-10T19:16:30.019158",
"End Time": "2025-04-10T19:16:50.112310",
"License Plate": [
"5691EX3"
]
}

View File

@ -0,0 +1,7 @@
{
"Start Time": "2025-04-10T19:43:56.756258",
"End Time": "2025-04-10T19:44:16.830570",
"License Plate": [
"5691EX3"
]
}

View File

@ -0,0 +1,7 @@
{
"Start Time": "2025-04-10T19:44:16.830570",
"End Time": "2025-04-10T19:44:36.902341",
"License Plate": [
"5691EX3"
]
}

View File

@ -0,0 +1,9 @@
{
"Start Time": "2025-04-10T19:44:36.902341",
"End Time": "2025-04-10T19:44:56.978730",
"License Plate": [
"9121CX7",
"E9121CX7",
"\u76969121CX7"
]
}

View File

@ -0,0 +1,17 @@
{
"Start Time": "2025-04-10T19:54:15.838565",
"End Time": "2025-04-10T19:54:35.847936",
"License Plate": [
"56918X3",
"\u76965691EK3",
"\u76965591EX3",
"9",
"5691EX",
"\u76965691EX3",
"5691EX3",
"5691X3",
"691EX3",
"5591EX3",
"569EX3"
]
}

View File

@ -0,0 +1,17 @@
{
"Start Time": "2025-04-11T00:42:20.435220",
"End Time": "2025-04-11T00:42:40.481205",
"License Plate": [
"9",
"5591EX3",
"5691EX3",
"\u76965691EK3",
"691EX3",
"569EX3",
"\u76965591EX3",
"5691X3",
"56918X3",
"5691EX",
"\u76965691EX3"
]
}

View File

@ -0,0 +1,17 @@
{
"Start Time": "2025-04-11T00:47:58.727056",
"End Time": "2025-04-11T00:48:18.912928",
"License Plate": [
"5691EX",
"569EX3",
"\u76965691EX3",
"5691X3",
"5691EX3",
"5591EX3",
"56918X3",
"\u76965691EK3",
"\u76965591EX3",
"9",
"691EX3"
]
}

View File

@ -0,0 +1,14 @@
{
"Start Time": "2025-04-11T00:48:18.912928",
"End Time": "2025-04-11T00:48:39.154114",
"License Plate": [
"5691EX",
"\u4e2d",
"\u76965691EX3",
"5691EX3",
"5601EX3",
"9",
"5691EX1",
"\u6d595691EX3"
]
}

View File

@ -0,0 +1,17 @@
{
"Start Time": "2025-04-11T00:51:08.175327",
"End Time": "2025-04-11T00:51:28.214272",
"License Plate": [
"9",
"\u76965691EK3",
"5691X3",
"\u76965591EX3",
"56918X3",
"5691EX3",
"569EX3",
"5591EX3",
"5691EX",
"\u76965691EX3",
"691EX3"
]
}

View File

@ -0,0 +1,14 @@
{
"Start Time": "2025-04-11T00:51:28.214272",
"End Time": "2025-04-11T00:51:48.479129",
"License Plate": [
"9",
"5691EX1",
"5691EX3",
"5601EX3",
"\u6d595691EX3",
"\u4e2d",
"5691EX",
"\u76965691EX3"
]
}

View File

@ -0,0 +1,9 @@
{
"Start Time": "2025-04-11T00:51:48.479129",
"End Time": "2025-04-11T00:52:08.692791",
"License Plate": [
"\u8d635691EX3",
"\u76965691EX3",
"5691EX3"
]
}

View File

@ -0,0 +1,7 @@
{
"Start Time": "2025-04-11T00:52:08.692791",
"End Time": "2025-04-11T00:52:28.960917",
"License Plate": [
"5691EX3"
]
}

1
app/api/v1/__init__.py Normal file
View File

@ -0,0 +1 @@
# from .endpoints.streaming import router as stream_router

View File

View File

@ -0,0 +1,193 @@
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import cv2
import asyncio
import base64
from services.ml.stream import stream, rstp_url
router = APIRouter(prefix="/app/v1", tags=["streaming"])
@router.get("/stream", response_class=HTMLResponse)
async def streaming():
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Car Plate Detection</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f2f5;
}
h1 {
color: #333;
margin-bottom: 20px;
}
.container {
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
max-width: 800px;
width: 100%;
}
#video_feed {
width: 100%;
border-radius: 8px;
margin-bottom: 15px;
}
.info-container {
display: flex;
justify-content: space-between;
margin-top: 15px;
}
#plate_number {
font-size: 18px;
font-weight: bold;
padding: 10px;
border-radius: 4px;
background-color: #e8e8e8;
flex: 1;
margin-right: 10px;
text-align: center;
}
#status {
font-size: 18px;
font-weight: bold;
padding: 10px;
border-radius: 4px;
flex: 1;
text-align: center;
}
.allowed {
background-color: #4CAF50;
color: white;
}
.denied {
background-color: #f44336;
color: white;
}
.error {
background-color: #ff9800;
color: white;
}
</style>
</head>
<body>
<div class="container">
<h1>Система контроля доступа</h1>
<img id="video_feed" src="" alt="Video Feed">
<div class="info-container">
<div id="plate_text">Ожидание номера...</div>
<div id="status">Ожидание...</div>
</div>
</div>
<script>
let ws;
function connect() {
ws = new WebSocket(`ws://${window.location.host}/app/v1/ws`);
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
document.getElementById("video_feed").src = "data:image/jpeg;base64," + data.frame;
const plateDiv = document.getElementById("plate_number");
const statusDiv = document.getElementById("status");
// Обновляем номер
if (data.plate_number) {
plateDiv.textContent = "Номер: " + data.plate_number;
} else {
plateDiv.textContent = "Ожидание номера...";
}
// Обновляем статус
if (data.status) {
statusDiv.textContent = data.status;
if (data.status === "ПРОЕЗД РАЗРЕШЕН") {
statusDiv.className = "allowed";
} else if (data.status.includes("ОШИБКА")) {
statusDiv.className = "error";
} else {
statusDiv.className = "denied";
}
}
};
ws.onclose = function() {
console.log('WebSocket closed. Reconnecting...');
setTimeout(connect, 1000);
};
ws.onerror = function(err) {
console.error('WebSocket error:', err);
ws.close();
};
}
connect();
</script>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
cap = cv2.VideoCapture(rstp_url)
if not cap.isOpened():
await websocket.send_json({
"frame": "",
"status": "ОШИБКА КАМЕРЫ",
"plate_number": ""
})
await websocket.close()
return
try:
while True:
ret, frame = cap.read()
if not ret:
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
continue
# Обработка кадра и получение статуса и номера
status, plate_number = stream(frame)
# Кодирование кадра в JPEG
_, buffer = cv2.imencode(".jpg", frame)
frame_base64 = base64.b64encode(buffer).decode("utf-8")
# Отправка кадра, статуса и номера через WebSocket
await websocket.send_json({
"frame": frame_base64,
"status": status,
"plate_number": plate_number
})
await asyncio.sleep(0.03) # ~30 FPS
except WebSocketDisconnect:
print("Client disconnected")
except Exception as e:
print(f"Error in websocket: {e}")
try:
await websocket.send_json({
"frame": "",
"status": "ОШИБКА СИСТЕМЫ",
"plate_number": ""
})
except:
pass
finally:
cap.release()
await websocket.close()

7
app/config/dev.yaml Normal file
View File

@ -0,0 +1,7 @@
database:
postgres:
port: 5432
dbName: "MyDBName"
hostname: "MyHostname"
user: "MyUser"
password: "MyPassword"

0
app/config/product.yaml Normal file
View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

BIN
app/images/images.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

BIN
app/images/korean_1.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

BIN
app/images/ru_plate1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

BIN
app/images/ru_plate2.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

BIN
app/images/ru_plate3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

50
app/main.py Normal file
View File

@ -0,0 +1,50 @@
import json
import cv2
# from ultralytics import YOLO
import numpy as np
import math
import re
import os
import sqlite3
from datetime import datetime
# from api.v1.endpoints.streaming import streaming
from api.v1.endpoints.streaming import router as stream_router
# from .api.v1.endpoints.streaming import router as steam_router - 'ээто работало
# from paddleocr import PaddleOCR
import uvicorn
from typing import Union
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# from pydantic import BaseModel
# class Item(BaseModel):
# name: str
# price: float
# is_offer: Union[bool, None] = None
app = FastAPI(title="Car Plate Detection API")
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Подключаем маршруты
app.include_router(stream_router)
@app.get("/")
async def root():
return {"message": "Welcome to the API"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
app/models/plate/best.pt Normal file

Binary file not shown.

BIN
app/original_plate.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
app/preprocessed_plate.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

2
app/services/__init__.py Normal file
View File

@ -0,0 +1,2 @@
# from .database.database import findCar
# from .ml.stream import stream

118
app/services/database.py Normal file
View File

@ -0,0 +1,118 @@
# import psycopg2
# from psycopg2.extras import DictCursor
# import os
# from dotenv import load_dotenv
# load_dotenv()
# class Database:
# def __init__(self):
# self.connection_params = {
# 'dbname': os.getenv('DB_NAME', 'kpp_db'),
# 'user': os.getenv('DB_USER', 'postgres'),
# 'password': os.getenv('DB_PASSWORD', ''),
# 'host': os.getenv('DB_HOST', 'localhost'),
# 'port': os.getenv('DB_PORT', '5432')
# }
# def test_connection(self):
# """Проверка подключения к базе данных"""
# try:
# with self.get_connection() as conn:
# with conn.cursor() as cur:
# # Проверяем существование таблицы
# cur.execute("""
# SELECT EXISTS (
# SELECT FROM information_schema.tables
# WHERE table_name = 'license_plates'
# );
# """)
# table_exists = cur.fetchone()[0]
# # Проверяем количество записей
# if table_exists:
# cur.execute("SELECT COUNT(*) FROM license_plates;")
# record_count = cur.fetchone()[0]
# return True, f"Подключение успешно. Записей в базе: {record_count}"
# else:
# return True, "Подключение успешно. Таблица 'license_plates' не существует."
# except Exception as e:
# return False, f"Ошибка подключения: {str(e)}"
# def get_connection(self):
# return psycopg2.connect(**self.connection_params)
# def findCar(self, plate_number: str) -> bool:
# try:
# with self.get_connection() as conn:
# with conn.cursor(cursor_factory=DictCursor) as cur:
# cur.execute(
# "SELECT EXISTS(SELECT 1 FROM license_plates WHERE plate_number = %s AND is_active = true)",
# (plate_number,)
# )
# return cur.fetchone()[0]
# except Exception as e:
# print(f"Database error in findCar: {e}")
# return False
# def add_car(self, plate_number: str, owner_name: str = None) -> bool:
# try:
# with self.get_connection() as conn:
# with conn.cursor() as cur:
# cur.execute(
# """
# INSERT INTO license_plates (plate_number, owner_name, is_active)
# VALUES (%s, %s, true)
# ON CONFLICT (plate_number)
# DO UPDATE SET is_active = true, owner_name = EXCLUDED.owner_name
# """,
# (plate_number, owner_name)
# )
# conn.commit()
# return True
# except Exception as e:
# print(f"Database error in add_car: {e}")
# return False
# def remove_car(self, plate_number: str) -> bool:
# try:
# with self.get_connection() as conn:
# with conn.cursor() as cur:
# cur.execute(
# "UPDATE license_plates SET is_active = false WHERE plate_number = %s",
# (plate_number,)
# )
# conn.commit()
# return True
# except Exception as e:
# print(f"Database error in remove_car: {e}")
# return False
# def init_db(self):
# """Initialize database tables if they don't exist"""
# try:
# with self.get_connection() as conn:
# with conn.cursor() as cur:
# cur.execute("""
# CREATE TABLE IF NOT EXISTS license_plates (
# plate_number VARCHAR(20) PRIMARY KEY,
# owner_name VARCHAR(100),
# is_active BOOLEAN DEFAULT true,
# created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
# updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
# )
# """)
# conn.commit()
# print("База данных успешно инициализирована")
# except Exception as e:
# print(f"Ошибка инициализации базы данных: {e}")
# database = Database()
# # Проверяем подключение при импорте модуля
# success, message = database.test_connection()
# print(f"Проверка базы данных: {message}")
# if success:
# database.init_db() # Инициализируем таблицы только если подключение успешно

View File

@ -0,0 +1 @@
# from .database import findCar

View File

@ -0,0 +1,160 @@
import psycopg2
from psycopg2.extras import DictCursor
import os
from dotenv import load_dotenv
load_dotenv()
class Database:
def __init__(self):
self.connection_params = {
'dbname': os.getenv('DB_NAME', 'kpp_db'),
'user': os.getenv('DB_USER', 'postgres'),
'password': os.getenv('DB_PASSWORD', ''),
'host': os.getenv('DB_HOST', 'localhost'),
'port': os.getenv('DB_PORT', '5432')
}
def test_connection(self):
"""Проверка подключения к базе данных"""
try:
with self.get_connection() as conn:
with conn.cursor() as cur:
# Проверяем существование таблицы
cur.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'license_plates'
);
""")
table_exists = cur.fetchone()[0]
# Проверяем количество записей
if table_exists:
cur.execute("SELECT COUNT(*) FROM license_plates;")
record_count = cur.fetchone()[0]
return True, f"Подключение успешно. Записей в базе: {record_count}"
else:
return True, "Подключение успешно. Таблица 'license_plates' не существует."
except Exception as e:
return False, f"Ошибка подключения: {str(e)}"
def get_connection(self):
return psycopg2.connect(**self.connection_params)
def findCar(self, plate_number: str) -> bool:
try:
with self.get_connection() as conn:
with conn.cursor(cursor_factory=DictCursor) as cur:
cur.execute(
"SELECT EXISTS(SELECT 1 FROM license_plates WHERE plate_number = %s AND is_active = true)",
(plate_number,)
)
return cur.fetchone()[0]
except Exception as e:
print(f"Database error in findCar: {e}")
return False
def add_car(self, plate_number: str, owner_name: str = None) -> bool:
try:
with self.get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"""
INSERT INTO license_plates (plate_number, owner_name, is_active)
VALUES (%s, %s, true)
ON CONFLICT (plate_number)
DO UPDATE SET is_active = true, owner_name = EXCLUDED.owner_name
""",
(plate_number, owner_name)
)
conn.commit()
return True
except Exception as e:
print(f"Database error in add_car: {e}")
return False
def remove_car(self, plate_number: str) -> bool:
try:
with self.get_connection() as conn:
with conn.cursor() as cur:
cur.execute(
"UPDATE license_plates SET is_active = false WHERE plate_number = %s",
(plate_number,)
)
conn.commit()
return True
except Exception as e:
print(f"Database error in remove_car: {e}")
return False
def init_db(self):
"""Initialize database tables if they don't exist"""
try:
with self.get_connection() as conn:
with conn.cursor() as cur:
cur.execute("""
CREATE TABLE IF NOT EXISTS license_plates (
plate_number VARCHAR(20) PRIMARY KEY,
owner_name VARCHAR(100),
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
print("База данных успешно инициализирована")
except Exception as e:
print(f"Ошибка инициализации базы данных: {e}")
database = Database()
# Проверяем подключение при импорте модуля
success, message = database.test_connection()
print(f"Проверка базы данных: {message}")
if success:
database.init_db() # Инициализируем таблицы только если подключение успешно
# import psycopg2
# connection = None
# try:
# connection = psycopg2.connect(
# dbname="car",
# user="postgres",
# password="qwerty12Q!",
# host="localhost",
# port="5432"
# )
# cursor = connection.cursor()
# except:
# print("Ошибка подключения")
# if connection == False:
# print("Соединение не установлено")
# def addLicensePlate(plate):
# cursor.execute("INSERT INTO cars plate VALUES %s", plate)
# def findCar(plate_number):
# # query = "SELECT EXISTS(SELECT * FROM cars WHERE plate = %s)"
# query = "SELECT * FROM cars WHERE plate = %s"
# cursor.execute(query, (plate_number))
# exists = cursor.fetchone()[0]
# cursor.close()
# connection.close()
# return exists

View File

@ -0,0 +1 @@
# from .stream import stream

464
app/services/ml/stream.py Normal file
View File

@ -0,0 +1,464 @@
import json
import cv2
from ultralytics import YOLO
import numpy as np
import math
import re
import os
import sqlite3
from datetime import datetime
from paddleocr import PaddleOCR
from ..database.database import database
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
rstp_url = "C:/kpp/app/images/шлагбаум1.mkv"
#Create a Video Capture Object
cap = cv2.VideoCapture(rstp_url)
#Initialize the YOLOv10 Model
model = YOLO("C:/kpp/app/models/kpp/yolo11s 10epochs/myyolo11s.pt")
#Initialize the frame count
count = 0
#Class Names
className = ["car","plate"]
#Initialize the Paddle OCR with optimized settings
ocr = PaddleOCR(use_angle_cls=True, lang='en', det=True, rec=True, cls=False, use_gpu=False)
# ocr = PaddleOCR(
# use_angle_cls=True,
# lang='en',
# det=True,
# rec=True,
# cls=False,
# use_gpu=False,
# show_log=False,
# rec_algorithm='SVTR_LCNet',
# rec_batch_num=1,
# det_db_thresh=0.3,
# det_db_box_thresh=0.5,
# det_db_unclip_ratio=1.6,
# max_batch_size=10,
# use_mp=True,
# total_process_num=2,
# check_point=False
# )
def preprocess_plate_image(plate_img):
try:
# Изменение размера (увеличение для лучшего распознавания)
height = plate_img.shape[0]
target_height = 100 # Уменьшаем высоту для лучшего распознавания
scale = target_height / height
width = int(plate_img.shape[1] * scale)
dim = (width, target_height)
resized = cv2.resize(plate_img, dim, interpolation=cv2.INTER_CUBIC)
# Преобразование в оттенки серого
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
# Нормализация гистограммы
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
normalized = clahe.apply(gray)
# Увеличение контраста
alpha = 1.3 # Уменьшаем контраст
beta = 30 # Увеличиваем яркость
contrast = cv2.convertScaleAbs(normalized, alpha=alpha, beta=beta)
# Размытие для уменьшения шума
blurred = cv2.GaussianBlur(contrast, (3, 3), 0)
# Адаптивная бинаризация
binary = cv2.adaptiveThreshold(
blurred,
255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY,
15, # Уменьшаем размер окна
5 # Уменьшаем константу
)
# Морфологические операции
kernel = np.ones((2,2), np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
# Добавляем белые поля
padding = 10
padded = cv2.copyMakeBorder(
binary,
padding, padding, padding, padding,
cv2.BORDER_CONSTANT,
value=255
)
# Сохраняем промежуточный результат для отладки
cv2.imwrite('preprocessed_plate.jpg', padded)
return padded
except Exception as e:
print(f"❌ Ошибка предобработки: {e}")
return plate_img
def clean_plate_text(text):
if not text:
return ""
# Удаление специальных символов и пробелов
text = re.sub(r'[^A-Za-z0-9А-Яа-я]', '', text)
# Замена похожих символов (русские на английские и наоборот)
replacements = {
# 'O': '0',
# 'I': '1',
# 'L': '1',
# 'Z': '2',
# 'S': '5',
# 'B': '8',
# 'D': '0',
# 'G': '6',
# # Русские буквы на английские
# 'А': 'A',
# 'В': 'B',
# 'Е': 'E',
# 'К': 'K',
# 'М': 'M',
# 'Н': 'H',
# 'О': 'O',
# 'Р': 'P',
# 'С': 'C',
# 'Т': 'T',
# 'У': 'Y',
# 'Х': 'X',
# # Нижний регистр
# 'a': 'A',
# 'b': 'B',
# 'c': 'C',
# 'd': 'D',
# 'e': 'E',
# 'h': 'H',
# 'k': 'K',
# 'm': 'M',
# 'o': 'O',
# 'p': 'P',
# 't': 'T',
# 'x': 'X',
# 'y': 'Y',
# Удаление специфических символов
'粤': '',
'u7696': '',
'|': '',
'/': '',
'\\': '',
'_': '',
'-': '',
'.': '',
' ': ''
}
# Применяем замены
for old, new in replacements.items():
text = text.replace(old, new)
# Приводим к верхнему регистру
text = text.upper()
# Удаляем все символы кроме букв и цифр
text = re.sub(r'[^A-Z0-9]', '', text)
# Удаляем повторяющиеся символы (например, '11' -> '1')
text = re.sub(r'(.)\1+', r'\1', text)
# Проверяем длину и структуру номера
if len(text) >= 3:
# Если номер начинается с буквы, за которой следуют только цифры
if re.match(r'^[A-Z][0-9]+$', text):
return text
# Если номер начинается с цифр, за которыми следуют буквы
elif re.match(r'^[0-9]+[A-Z]+$', text):
return text
# Если номер имеет смешанную структуру (буквы и цифры)
elif re.match(r'^[A-Z0-9]{3,}$', text):
return text
# Если текст не соответствует ожидаемой структуре, возвращаем пустую строку
return ""
def paddle_ocr(frame, x1, y1, x2, y2):
try:
# Вырезаем область с номером с дополнительным отступом
height = y2 - y1
width = x2 - x1
y1_pad = max(0, y1 - int(height))
y2_pad = min(frame.shape[0], y2 + int(height))
x1_pad = max(0, x1 - int(width ))
x2_pad = min(frame.shape[1], x2 + int(width ))
plate_region = frame[y1_pad:y2_pad, x1_pad:x2_pad]
# Сохраняем оригинальное изображение для отладки
cv2.imwrite('original_plate.jpg', plate_region)
# Предварительная обработка изображения
processed_img = preprocess_plate_image(plate_region)
# Распознавание текста
results = ocr.ocr(processed_img, det=True, rec=True, cls=False)
print(f"OCR результаты: {results}")
if not results or not results[0]:
print("❌ Текст не обнаружен")
return "", 0
# Собираем все распознанные тексты и их уверенности
texts = []
confidences = []
for line in results[0]: # Берем первый результат из списка
if line:
# В новом формате PaddleOCR возвращает [points, (text, confidence)]
text = line[1][0] # Получаем текст
conf = float(line[1][1]) # Получаем уверенность
print(f"Найден текст: {text}")
print(f"Уверенность: {conf*100:.1f}%")
# Очистка и нормализация текста
cleaned_text = clean_plate_text(text)
print(f"Очищенный текст: {cleaned_text}")
if cleaned_text:
texts.append(cleaned_text)
confidences.append(conf)
print("✅ Текст принят")
else:
print("❌ Текст отклонен (слишком короткий или пустой)")
if not texts:
print("❌ Нет подходящих вариантов текста")
return "", 0
# Выбираем текст с наивысшей уверенностью
best_idx = np.argmax(confidences)
best_text = texts[best_idx]
best_conf = confidences[best_idx]
print(f"✅ Лучший вариант: {best_text} ({best_conf*100:.1f}%)")
return best_text, best_conf
except Exception as e:
print(f"❌ Ошибка OCR: {str(e)}")
print(f"Тип ошибки: {type(e).__name__}")
return "", 0
def save_json(license_plates, startTime, endTime):
#Generate individual JSON files for each 20-second interval
interval_data = {
"Start Time": startTime.isoformat(),
"End Time": endTime.isoformat(),
"License Plate": list(license_plates)
}
interval_file_path = "../../api/json/output_" + datetime.now().strftime("%Y%m%d%H%M%S") + ".json"
with open(interval_file_path, 'w') as f:
json.dump(interval_data, f, indent = 2)
#Cummulative JSON File
cummulative_file_path = "json/LicensePlateData.json"
if os.path.exists(cummulative_file_path):
with open(cummulative_file_path, 'r') as f:
existing_data = json.load(f)
else:
existing_data = []
#Add new intervaal data to cummulative data
existing_data.append(interval_data)
with open(cummulative_file_path, 'w') as f:
json.dump(existing_data, f, indent = 2)
#Save data to SQL database
# save_to_database(license_plates, startTime, endTime)
# def save_to_database(license_plates, start_time, end_time):
# conn = sqlite3.connect('licensePlatesDatabase.db')
# cursor = conn.cursor()
# for plate in license_plates:
# cursor.execute('''
# INSERT INTO LicensePlates(start_time, end_time, license_plate)
# VALUES (?, ?, ?)
# ''', (start_time.isoformat(), end_time.isoformat(), plate))
# conn.commit()
# conn.close()
def stream(frame):
try:
status = "НЕТ В СПИСКЕ"
plate_text = ""
results = model.predict(frame, conf=0.30) # Снижаем порог детекции
for result in results:
boxes = result.boxes
for box in boxes:
x1, y1, x2, y2 = box.xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
classNameInt = int(box.cls[0])
conf = math.ceil(box.conf[0] * 100) / 100
if className[classNameInt] == "plate" and conf >= 0.30:
print("\n" + "="*70)
print(f"🚗 ОБНАРУЖЕН НОМЕРНОЙ ЗНАК (уверенность детекции: {conf*100:.1f}%)")
# Сохраняем оригинальные координаты для отрисовки
orig_box = (x1, y1, x2, y2)
# Увеличиваем область для OCR
height = y2 - y1
width = x2 - x1
# Расширяем область для OCR на 20%
ocr_x1 = max(0, x1 - int(width))
ocr_y1 = max(0, y1 - int(height))
ocr_x2 = min(frame.shape[1], x2 + int(width))
ocr_y2 = min(frame.shape[0], y2 + int(height))
# Рисуем рамку по оригинальным координатам
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
# Распознаем текст номера с расширенной областью
text, ocr_confidence = paddle_ocr(frame, ocr_x1, ocr_y1, ocr_x2, ocr_y2)
print(f"Распознанный текст: {text}")
print(f"Уверенность OCR: {ocr_confidence*100:.1f}%")
if text and ocr_confidence >= 0.60:
plate_text = text
try:
permission = database.findCar(text)
status = "ПРОЕЗД РАЗРЕШЕН" if permission else "НЕТ В СПИСКЕ"
print(f"Статус: {status}")
# Настраиваем отображение
text_color = (0, 255, 0) if permission else (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.7
thickness = 2
# Текст номера над рамкой
plate_label = f"{text} ({int(ocr_confidence * 100)}%)"
text_size = cv2.getTextSize(plate_label, font, font_scale, thickness)[0]
# Фон для текста номера
cv2.rectangle(frame,
(x1, y1 - text_size[1] - 10),
(x1 + text_size[0], y1),
text_color, -1)
# Текст номера
cv2.putText(frame, plate_label,
(x1, y1 - 5),
font, font_scale, (255, 255, 255),
thickness, cv2.LINE_AA)
# Статус под рамкой
status_size = cv2.getTextSize(status, font, font_scale, thickness)[0]
# Фон для статуса
cv2.rectangle(frame,
(x1, y2),
(x1 + status_size[0], y2 + status_size[1] + 10),
text_color, -1)
# Текст статуса
cv2.putText(frame, status,
(x1, y2 + status_size[1] + 5),
font, font_scale, (255, 255, 255),
thickness, cv2.LINE_AA)
except Exception as e:
print(f"❌ Ошибка базы данных: {str(e)}")
status = "ОШИБКА ПРОВЕРКИ"
else:
print("❌ Текст не распознан или низкая уверенность")
elif className[classNameInt] == "car":
# Рисуем рамку вокруг машины зеленым цветом
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
return status, plate_text
except Exception as e:
print(f"❌ Ошибка обработки: {str(e)}")
return "ОШИБКА ОБРАБОТКИ", ""
# def stream(frame):
# startTime = datetime.now()
# license_plates = set()
# while True:
# ret, frame = cap.read()
# if ret:
# currentTime = datetime.now()
# count += 1
# print(f"Frame Number: {count}")
# results = model.predict(frame, conf = 0.45)
# for result in results:
# boxes = result.boxes
# for box in boxes:
# x1, y1, x2, y2 = box.xyxy[0]
# x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
# cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
# classNameInt = int(box.cls[0])
# clsName = className[classNameInt]
# conf = math.ceil(box.conf[0]*100)/100
# #label = f'{clsName}:{conf}'
# label = paddle_ocr(frame, x1, y1, x2, y2)
# if label:
# license_plates.add(label)
# textSize = cv2.getTextSize(label, 0, fontScale=0.5, thickness=2)[0]
# c2 = x1 + textSize[0], y1 - textSize[1] - 3
# cv2.rectangle(frame, (x1, y1), c2, (255, 0, 0), -1)
# cv2.putText(frame, label, (x1, y1 - 2), 0, 0.5, [255,255,255], thickness=1, lineType=cv2.LINE_AA)
# if conf >= 70:
# permistion = database.findCar(label)
# if permistion == True:
# text = "ПРОЕЗД РАЗРЕШЕН"
# return text
# else:
# text = "НЕТ В СПИСКЕ"
# return text
# if (currentTime - startTime).seconds >= 20:
# endTime = currentTime
# save_json(license_plates, startTime, endTime)
# startTime = currentTime
# license_plates.clear()
# cv2.imshow("Video", frame)
# if cv2.waitKey(1) & 0xFF == ord('1'):
# break
# else:
# break
# cap.release()
# cv2.destroyAllWindows()

36
app/test_db.py Normal file
View File

@ -0,0 +1,36 @@
from services.database.database import database # Исправленный путь импорта
def test_database():
print("\n=== Тестирование базы данных ===")
# Проверка подключения
success, message = database.test_connection()
print(f"\n1. Проверка подключения:")
print(f"Результат: {message}")
if success:
# Тестовые данные
test_plates = [
("A123BC", "Test Owner 1"),
("B456CD", "Test Owner 2"),
("C789EF", "Test Owner 3")
]
print("\n2. Добавление тестовых номеров:")
for plate, owner in test_plates:
if database.add_car(plate, owner):
print(f"Номер {plate} успешно добавлен")
else:
print(f"Ошибка при добавлении номера {plate}")
print("\n3. Проверка наличия номеров:")
for plate, _ in test_plates:
if database.findCar(plate):
print(f"Номер {plate} найден в базе")
else:
print(f"Номер {plate} не найден в базе")
print("\n=== Тестирование завершено ===\n")
if __name__ == "__main__":
test_database()

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi==0.104.1
uvicorn==0.24.0
opencv-python==4.8.1.78
numpy==1.26.2
ultralytics==8.0.208
paddlepaddle==2.5.2
paddleocr==2.7.0.3
psycopg2-binary==2.9.9
python-dotenv==1.0.0