Compare commits

...

10 Commits
main ... dev

57 changed files with 348 additions and 848 deletions

16
.env
View File

@ -1,7 +1,11 @@
DB_NAME=dbname
DB_USER=username
DB_PASSWORD=urpassword
DB_HOST=localhost
DB_PORT=5432
RTSP_URL=rtsp://192.168.31.56:8554/cam
# YOLO_MODEL=/home/app/ml/models/kpp/yolo11n_10_epochs/yolo11n_10epochs.pt
YOLO_MODEL=C:\project\kpp\app\ml\models\kpp\yolo11n_10_epochs\yolo11n_10epochs.pt
WEB_IP_ADDR=192.168.31.56:8001
WEB_TOKEN=local-test-key
REDIS_HOST=192.168.31.56
REDIS_PORT=6379
RTSP_URL=C:/kpp/app/images/шлагбаум1.mkv # путь к камере (пока что только видео)

2
.gitignore vendored
View File

@ -14,7 +14,7 @@ test.db
log.txt
Pipfile.lock
env3.*
env
.env
docs_build
site_build
venv

10
app/.dockerignore Normal file
View File

@ -0,0 +1,10 @@
__pycache__/
*.pyc
*.pyo
*.pyd
*.log
.tmp
.env
.local

57
app/Dockerfile Normal file
View File

@ -0,0 +1,57 @@
###########
# BUILDER #
###########
# pull official base image
FROM python:3.10 as builder
# set work directory
WORKDIR /usr/src/app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc
# install python dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt
#########
# FINAL #
#########
# pull official base image
FROM python:3.10
# create directory for the app user
RUN mkdir -p /home/app
# create the app user
RUN addgroup --system app && adduser --system --group app
# create the appropriate directories
ENV HOME=/home/app
WORKDIR $HOME
# install dependencies
RUN apt-get update && apt-get install -y --no-install-recommends netcat-traditional
COPY --from=builder /usr/src/app/wheels /wheels
COPY --from=builder /usr/src/app/requirements.txt .
RUN pip install --upgrade pip
RUN pip install --no-cache /wheels/*
RUN apt install libgl1 -y
RUN apt install libglib2.0-0 -y
# copy project
COPY . $HOME
RUN chown -R app:app $HOME
# USER app
ENV NO_AVX=1

View File

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

View File

@ -1,137 +0,0 @@
[
{
"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

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

View File

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

View File

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

View File

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

View File

@ -1,17 +0,0 @@
{
"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

@ -1,17 +0,0 @@
{
"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

@ -1,17 +0,0 @@
{
"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

@ -1,14 +0,0 @@
{
"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

@ -1,17 +0,0 @@
{
"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

@ -1,14 +0,0 @@
{
"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

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

View File

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

View File

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

View File

@ -1,193 +0,0 @@
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()

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 655 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

View File

@ -1,30 +1,20 @@
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
import sys
import os
from pathlib import Path
from api.v1.endpoints.streaming import router as stream_router
# from .api.v1.endpoints.streaming import router as steam_router - 'ээто работало
# Добавляем корневую директорию проекта в PYTHONPATH
project_root = str(Path(__file__).parent.parent)
if project_root not in sys.path:
sys.path.append(project_root)
from app.api.v1.endpoints.streaming import router as stream_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")
@ -40,7 +30,6 @@ app.add_middleware(
# Подключаем маршруты
app.include_router(stream_router)
@app.get("/")
async def root():
return {"message": "Welcome to the API"}

34
app/ml/data_models.py Normal file
View File

@ -0,0 +1,34 @@
class BaseData:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
@property
def width(self) -> float:
return self.x2 - self.x1
@property
def height(self) -> float:
return self.y2 - self.y1
@property
def area(self) -> float:
return self.width * self.height
def get_center(self) -> tuple[float, float]:
return ((self.x1 + self.x2) / 2, (self.y1 + self.y2) / 2)
class Plate(BaseData):
def __init__(self, number: str, x1, y1, x2, y2):
self.number = number
super().__init__(x1, y1, x2, y2)
class Car(BaseData):
pass

212
app/ml/streaming.py Normal file
View File

@ -0,0 +1,212 @@
import av
import json
from ultralytics import YOLO
from paddleocr import PaddleOCR
import cv2
import numpy as np
import re
import os
from dotenv import load_dotenv
import requests
from data_models import Car, Plate, BaseData
import time
import redis
from urllib.parse import urlparse
load_dotenv()
redis_host = os.getenv('REDIS_HOST', 'localhost')
redis_port = int(os.getenv('REDIS_PORT', '6379'))
redis_con = redis.Redis(
host=redis_host,
port=redis_port,
decode_responses=True
)
rstp_url= os.getenv('RTSP_URL')
#лучший вариант kpp\app\ml\models\kpp\yolo11s 10epochs\myyolo11s.pt
yolo_model= os.getenv('YOLO_MODEL', r'C:\project\kpp\app\ml\models\kpp\yolo11n 20 eposhs\best.pt')
token= os.getenv('WEB_TOKEN')
ip_addr_web= os.getenv('WEB_IP_ADDR')
# Загрузка YOLO-модели
model = YOLO(yolo_model)
# Инициализация PaddleOCR
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
classNames = ["car", "plate"]
def clean_plate_text(text):
if not text:
return ""
text = re.sub(r'[^\w\s]', '', text)
allowed_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ0123456789')
text = ''.join(c for c in text.upper() if c in allowed_chars)
if len(text) < 4:
return ""
ru_pattern = r'^([A-ZА-Я])\s?([0-9]{3})\s?([A-ZА-Я]{2})\s?([0-9]{2,3})$'
general_pattern = r'^[A-ZА-Я0-9]{4,}$'
if re.match(ru_pattern, text) or re.match(general_pattern, 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]
if plate_region.size == 0:
print("❌ Пустая область номера")
return ""
results = ocr.ocr(plate_region, det=True, rec=True, cls=False)
if not results or not results[0]:
print("❌ Текст не обнаружен")
return ""
full_text = ""
for line in results[0]:
if line:
text = line[1][0]
conf = line[1][1]
print(f"Найден текст: {text} (уверенность: {conf*100:.1f}%)")
full_text += " " + text # Склеиваем все куски текста через пробел
full_text = full_text.strip()
print(f"📦 Собранный текст перед очисткой: {full_text}")
cleaned_text = clean_plate_text(full_text)
if cleaned_text:
print(f"✅ Очищенный текст: {cleaned_text}")
return cleaned_text
else:
print("❌ Текст отклонен после объединения")
return ""
except Exception as e:
print(f"❌ Ошибка OCR: {str(e)}")
return ""
def json_packer(type, data: BaseData):
try:
data = {
'type': type,
"coordinates" : [
data.x1,
data.y1
],
"width" : data.width,
"height" : data.height
}
return data
except Exception as e:
error_msg = f"Ошибка при формировании данных: {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
def server_ping():
try:
url = f"http://{ip_addr_web}/start_recieve"
headers = {
'Authorization': f'',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers)
except Exception as e:
error_msg = f"Ошибка при формировании данных: {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
def data_upload_redis(value, key='ai_recieve'):
try:
value = json.dumps(value)
print(value)
redis_con.lpush(key, value)
except Exception as e:
error_msg = f"Ошибка {str(e)}"
print(f"\n❌ {error_msg}")
return {
"error": error_msg
}
plate = Plate("", 0, 0, 0, 0)
car = Car(0,0,0,0)
container = av.open(
rstp_url, 'r',
options={
'rtsp_transport': 'tcp', # при udp теряются пакеты
'fflags': 'nobuffer', # отключаем буферизацию
'flags': 'low_delay', # оставшиеся настройки для снижения задержки
'stimeout': '100000',
'max_delay': '100000',
}
)
video = container.demux(video=0)
video_stream = next(s for s in container.streams if s.type == 'video')
server_ping()
for packet in container.demux(video_stream):
for frame in packet.decode():
if 'start_time' not in locals():
start_time = time.time()
start_read = frame.time
if (time.time()-start_time)-(frame.time-start_read)>.3:
continue # пропуск кадров при отставании от real time
pts = time.time()
img = frame.to_ndarray(format='bgr24')
results = model.predict(img)
data = {'pts': pts,
'content': {'content': []},
'plate_text': []}
for result in results:
for box in result.boxes:
x1, y1, x2, y2 = map(int,box.xyxy[0])
# выводит данные о классе 'plate'
if box.cls == 0 and box.conf >= 0.2:
text = paddle_ocr(img, x1, y1, x2, y2)
plate = Plate(text, x1, y1, x2, y2)
data['content']['content'].append(json_packer(int(box.cls), plate))
data['plate_text'].append(text)
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
# выводит данные о классе 'car'
elif box.cls == 1 and box.conf >= 0.50:
car = Car(x1, y1, x2, y2)
data['content']['content'].append(json_packer(int(box.cls), car))
# cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
data_upload_redis(data)
# cv2.imshow('frame', img)
# if cv2.waitKey(1) & 0xFF == ord('q'):
# cv2.destroyAllWindows()
# container.close()
# break

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

8
app/requirements.txt Normal file
View File

@ -0,0 +1,8 @@
opencv-python-headless==4.11.0.86
numpy==1.26.2
ultralytics==8.3.111
paddlepaddle==3.0.0
paddleocr==2.10.0
python-dotenv==1.0.0
pyav==14.2.1
redis==5.2.1

View File

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

View File

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

View File

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

View File

@ -1,285 +0,0 @@
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
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
rstp_url = "C:/kpp/app/images/шлагбаум1.mkv"
# Создаем объект видеозахвата
cap = cv2.VideoCapture(rstp_url)
# Инициализируем модель YOLO
model = YOLO("C:/kpp/app/models/kpp/yolo11s 10epochs/myyolo11s.pt")
# Счетчик кадров
count = 0
# Названия классов
className = ["car", "plate"]
# Инициализируем PaddleOCR с оптимизированными параметрами
#Initialize the Paddle OCR
ocr = PaddleOCR(use_angle_cls = True, use_gpu = False)
# ocr = PaddleOCR(
# use_angle_cls=True,
# lang='ch', # Используем 'ch' как базовый, но с кастомной моделью для мультиязычности
# det=True,
# rec=True,
# cls=False,
# use_gpu=False,
# det_db_thresh=0.3,
# det_db_box_thresh=0.5,
# det_db_unclip_ratio=1.5,
# max_batch_size=1,
# rec_batch_num=1
# )
def preprocess_plate_image(plate_img):
try:
# Проверяем, что изображение не пустое
if plate_img.size == 0:
print("❌ Пустое изображение номера")
return plate_img
# Изменение размера для улучшения читаемости
height = plate_img.shape[0]
target_height = 120 # Увеличиваем высоту для лучшего распознавания
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
clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(8, 8))
normalized = clahe.apply(gray)
# Увеличение контраста
alpha = 1.2
beta = 20
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_INV, # Используем инверсию для темного текста
11,
2
)
# Морфологические операции для очистки
kernel = np.ones((2, 2), np.uint8)
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=1)
# Добавляем белые поля
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'[^\w\s]', '', text)
# Разрешенные символы (русские и английские буквы, цифры)
allowed_chars = set('ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ0123456789')
text = ''.join(c for c in text.upper() if c in allowed_chars)
# Проверяем типичные форматы номеров
# Российский формат: А123БВ456 или 123АБ456
ru_pattern = r'^[А-Я][0-9]{3}[А-Я]{2}[0-9]{2,3}$|^[0-9]{3}[А-Я]{2}[0-9]{2,3}$'
# Общий формат: минимум 3 символа букв и цифр
general_pattern = r'^[A-ZА-Я0-9]{3,}$'
if re.match(ru_pattern, text) or re.match(general_pattern, 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 * 0.3))
y2_pad = min(frame.shape[0], y2 + int(height * 0.3))
x1_pad = max(0, x1 - int(width * 0.3))
x2_pad = min(frame.shape[1], x2 + int(width * 0.3))
plate_region = frame[y1_pad:y2_pad, x1_pad:x2_pad]
# Проверяем, что регион не пустой
if plate_region.size == 0:
print("❌ Пустая область номера")
return "", 0
# Сохраняем для отладки
cv2.imwrite('original_plate.jpg', plate_region)
# Предобработка изображения
# processed_img = preprocess_plate_image(plate_region)
# Распознавание текста
results = ocr.ocr(plate_region, 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:
text = line[1][0]
conf = float(line[1][1])
print(f"Найден текст: {text} (уверенность: {conf*100:.1f}%)")
cleaned_text = clean_plate_text(text)
if cleaned_text:
texts.append(cleaned_text)
confidences.append(conf)
print(f"Очищенный текст: {cleaned_text}")
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)}")
return "", 0
def save_json(license_plates, startTime, endTime):
interval_data = {
"Start Time": startTime.isoformat(),
"End Time": endTime.isoformat(),
"License Plate": list(license_plates)
}
interval_file_path = f"../../api/json/output_{datetime.now().strftime('%Y%m%d%H%M%S')}.json"
with open(interval_file_path, 'w', encoding='utf-8') as f:
json.dump(interval_data, f, indent=2, ensure_ascii=False)
cummulative_file_path = "json/LicensePlateData.json"
existing_data = []
if os.path.exists(cummulative_file_path):
with open(cummulative_file_path, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
existing_data.append(interval_data)
with open(cummulative_file_path, 'w', encoding='utf-8') as f:
json.dump(existing_data, f, indent=2, ensure_ascii=False)
def stream(frame):
try:
status = "НЕТ В СПИСКЕ"
plate_text = ""
results = model.predict(frame, conf=0.80) # Снижаем порог для лучшей детекции
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.50:
print("\n" + "="*70)
print(f"🚗 Номерной знак обнаружен (уверенность: {conf*100:.1f}%)")
# Рисуем рамку
cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 0), 2)
# Распознаем текст
text, ocr_confidence = paddle_ocr(frame, x1, y1, x2, y2)
print(f"Распознанный текст: {text} ({ocr_confidence*100:.1f}%)")
if text and ocr_confidence >= 0.70: # Снижаем порог уверенности
plate_text = text
# Здесь должна быть проверка в базе данных
# permission = database.findCar(text)
permission = False # Заглушка
status = "ПРОЕЗД РАЗРЕШЕН" if permission else "НЕТ В СПИСКЕ"
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)
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 "ОШИБКА ОБРАБОТКИ", ""

View File

@ -1,36 +0,0 @@
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()

7
docker-compose.yml Normal file
View File

@ -0,0 +1,7 @@
services:
ai-service:
command: ["python", "ml/streaming.py", ]
build: ./app
restart: always
env_file:
- .env

View File

@ -1,9 +0,0 @@
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