striming pyav
This commit is contained in:
parent
cdf886725f
commit
7e55e72e35
2
.env
2
.env
@ -4,7 +4,7 @@ DB_PASSWORD=qwerty12Q!
|
|||||||
DB_HOST=localhost
|
DB_HOST=localhost
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
|
|
||||||
RTSP_URL=C:/kpp/шлагбаум1.mkv
|
RTSP_URL=C:/kpp/app/ml/video.mkv
|
||||||
|
|
||||||
YOLO_MODEL=C:/kpp/app/ml/models/kpp/yolo11s 10epochs/myyolo11s.pt
|
YOLO_MODEL=C:/kpp/app/ml/models/kpp/yolo11s 10epochs/myyolo11s.pt
|
||||||
|
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"Start Time": "2025-04-10T19:16:30.019158",
|
|
||||||
"End Time": "2025-04-10T19:16:50.112310",
|
|
||||||
"License Plate": [
|
|
||||||
"5691EX3"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"Start Time": "2025-04-10T19:43:56.756258",
|
|
||||||
"End Time": "2025-04-10T19:44:16.830570",
|
|
||||||
"License Plate": [
|
|
||||||
"5691EX3"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"Start Time": "2025-04-10T19:44:16.830570",
|
|
||||||
"End Time": "2025-04-10T19:44:36.902341",
|
|
||||||
"License Plate": [
|
|
||||||
"5691EX3"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
{
|
|
||||||
"Start Time": "2025-04-11T00:52:08.692791",
|
|
||||||
"End Time": "2025-04-11T00:52:28.960917",
|
|
||||||
"License Plate": [
|
|
||||||
"5691EX3"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@ -1 +0,0 @@
|
|||||||
# from .endpoints.streaming import router as stream_router
|
|
||||||
@ -1 +0,0 @@
|
|||||||
|
|
||||||
@ -1,226 +0,0 @@
|
|||||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
|
||||||
from fastapi.responses import HTMLResponse
|
|
||||||
import cv2
|
|
||||||
import asyncio
|
|
||||||
import base64
|
|
||||||
import os
|
|
||||||
import logging
|
|
||||||
from app.ml.stream import stream
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
|
|
||||||
# Настройка логирования
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
router = APIRouter(prefix="/app/v1", tags=["streaming"])
|
|
||||||
|
|
||||||
rstp_url = os.getenv("RTSP_URL")
|
|
||||||
|
|
||||||
if not rstp_url:
|
|
||||||
raise ValueError("RTSP_URL не задан в .env файле")
|
|
||||||
|
|
||||||
@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;
|
|
||||||
let reconnectAttempts = 0;
|
|
||||||
const maxReconnectAttempts = 5;
|
|
||||||
|
|
||||||
function connect() {
|
|
||||||
if (reconnectAttempts >= maxReconnectAttempts) {
|
|
||||||
console.error('Превышено максимальное количество попыток подключения');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
ws = new WebSocket(`ws://${window.location.host}/app/v1/ws`);
|
|
||||||
|
|
||||||
ws.onmessage = function(event) {
|
|
||||||
reconnectAttempts = 0;
|
|
||||||
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...');
|
|
||||||
reconnectAttempts++;
|
|
||||||
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()
|
|
||||||
logger.info("WebSocket соединение установлено")
|
|
||||||
|
|
||||||
try:
|
|
||||||
if not os.path.exists(rstp_url):
|
|
||||||
|
|
||||||
raise FileNotFoundError(f"Видеофайл не найден: {rstp_url}")
|
|
||||||
|
|
||||||
cap = cv2.VideoCapture(rstp_url)
|
|
||||||
if not cap.isOpened():
|
|
||||||
raise RuntimeError("Не удалось открыть видеопоток")
|
|
||||||
|
|
||||||
logger.info("Видеопоток успешно открыт")
|
|
||||||
|
|
||||||
while True:
|
|
||||||
ret, frame = cap.read()
|
|
||||||
if not ret:
|
|
||||||
logger.debug("Достигнут конец видео, перезапуск")
|
|
||||||
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
|
|
||||||
})
|
|
||||||
|
|
||||||
# Задержка для контроля FPS
|
|
||||||
await asyncio.sleep(0.03) # ~30 FPS
|
|
||||||
|
|
||||||
except FileNotFoundError as e:
|
|
||||||
logger.error(f"Ошибка файла: {str(e)}")
|
|
||||||
await websocket.send_json({
|
|
||||||
"frame": "",
|
|
||||||
"status": "ОШИБКА: Видеофайл не найден",
|
|
||||||
"plate_number": ""
|
|
||||||
})
|
|
||||||
except WebSocketDisconnect:
|
|
||||||
logger.info("Клиент отключился")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Ошибка в WebSocket: {str(e)}")
|
|
||||||
try:
|
|
||||||
await websocket.send_json({
|
|
||||||
"frame": "",
|
|
||||||
"status": "ОШИБКА СИСТЕМЫ",
|
|
||||||
"plate_number": ""
|
|
||||||
})
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
finally:
|
|
||||||
logger.info("Закрытие соединения")
|
|
||||||
if 'cap' in locals():
|
|
||||||
cap.release()
|
|
||||||
await websocket.close()
|
|
||||||
|
|
||||||
26
app/ml/Car.py
Normal file
26
app/ml/Car.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
class Car():
|
||||||
|
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)
|
||||||
26
app/ml/Plate.py
Normal file
26
app/ml/Plate.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
class Plate():
|
||||||
|
def __init__(self, number: str, x1, y1, x2, y2):
|
||||||
|
self.number = number
|
||||||
|
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)
|
||||||
358
app/ml/stream.py
358
app/ml/stream.py
@ -1,358 +0,0 @@
|
|||||||
import json
|
|
||||||
import cv2
|
|
||||||
from ultralytics import YOLO
|
|
||||||
import numpy as np
|
|
||||||
import math
|
|
||||||
import re
|
|
||||||
import os
|
|
||||||
import requests
|
|
||||||
from datetime import datetime
|
|
||||||
from paddleocr import PaddleOCR
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
|
|
||||||
load_dotenv()
|
|
||||||
|
|
||||||
token = os.getenv('token')
|
|
||||||
|
|
||||||
yolo_model = os.getenv('YOLO_MODEL')
|
|
||||||
|
|
||||||
ip_addr_web = os.getenv('ip_addr_web')
|
|
||||||
|
|
||||||
rstp_url = os.getenv("RTSP_URL")
|
|
||||||
# from services.database.database import database
|
|
||||||
|
|
||||||
# os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
|
||||||
|
|
||||||
|
|
||||||
# Создаем объект видеозахвата
|
|
||||||
cap = cv2.VideoCapture(rstp_url)
|
|
||||||
|
|
||||||
# Инициализируем модель YOLO
|
|
||||||
model = YOLO(yolo_model)
|
|
||||||
|
|
||||||
# Счетчик кадров
|
|
||||||
count = 0
|
|
||||||
|
|
||||||
# Названия классов
|
|
||||||
className = ["car", "plate"]
|
|
||||||
|
|
||||||
# Инициализируем PaddleOCR с оптимизированными параметрами
|
|
||||||
#Initialize the Paddle OCR
|
|
||||||
ocr = PaddleOCR(use_angle_cls = True, use_gpu = False)
|
|
||||||
|
|
||||||
#настройки для PaddleOCR
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
# Проверяем минимальную длину номера
|
|
||||||
if len(text) < 4:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
# Проверяем типичные форматы номеров
|
|
||||||
# Российский формат: А123БВ456 или 123АБ456
|
|
||||||
ru_pattern = r'^[А-Я][0-9]{3}[А-Я]{2}[0-9]{2,3}$|^[0-9]{3}[А-Я]{2}[0-9]{2,3}$'
|
|
||||||
# Общий формат: минимум 4 символа букв и цифр
|
|
||||||
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 * 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 send_car_data(plate_text, x1, y1, x2, y2):
|
|
||||||
"""Отправка данных об автомобиле на сервер"""
|
|
||||||
try:
|
|
||||||
url = f"http://{ip_addr_web}/recieve_data_from_ai"
|
|
||||||
|
|
||||||
width = x2 - x1
|
|
||||||
height = y2 - y1
|
|
||||||
|
|
||||||
data = {
|
|
||||||
"plate_number": plate_text,
|
|
||||||
"coordinates": [
|
|
||||||
x1,
|
|
||||||
y1
|
|
||||||
],
|
|
||||||
"width": width,
|
|
||||||
"height": height
|
|
||||||
}
|
|
||||||
|
|
||||||
payload = json.dumps(data)
|
|
||||||
|
|
||||||
headers = {
|
|
||||||
'Authorization': f'{token}',
|
|
||||||
'Content-Type': 'application/json'
|
|
||||||
}
|
|
||||||
|
|
||||||
print("\n=== Отправка данных на сервер ===")
|
|
||||||
print(f"URL: {url}")
|
|
||||||
print(f"Номер: {plate_text}")
|
|
||||||
print(f"Координаты: x={x1}, y={y1}")
|
|
||||||
print(f"Размеры: {width}x{height}")
|
|
||||||
print("================================")
|
|
||||||
|
|
||||||
response = requests.request("POST", url, headers=headers, data=payload)
|
|
||||||
|
|
||||||
print("\n=== Ответ сервера ===")
|
|
||||||
print(f"Статус: {response.status_code}")
|
|
||||||
print(f"Ответ: {response.text}")
|
|
||||||
print("====================")
|
|
||||||
|
|
||||||
return {
|
|
||||||
"sent_data": data,
|
|
||||||
"response": {
|
|
||||||
"status_code": response.status_code,
|
|
||||||
"text": response.text
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
error_msg = f"Ошибка при отправке данных: {str(e)}"
|
|
||||||
print(f"\n❌ {error_msg}")
|
|
||||||
return {
|
|
||||||
"error": error_msg
|
|
||||||
}
|
|
||||||
|
|
||||||
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.90)
|
|
||||||
|
|
||||||
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.90:
|
|
||||||
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(str(plate_text))
|
|
||||||
# TODO: реализовать проверку в базе данных
|
|
||||||
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)
|
|
||||||
send_car_data(plate_text, x1, y1, x2, y2)
|
|
||||||
|
|
||||||
return status, plate_text
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"❌ Ошибка обработки: {str(e)}")
|
|
||||||
return "ОШИБКА ОБРАБОТКИ", ""
|
|
||||||
204
app/ml/streaming.py
Normal file
204
app/ml/streaming.py
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
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 Car import Car
|
||||||
|
from Plate import Plate
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
rstp_url= os.getenv('RTSP_URL')
|
||||||
|
|
||||||
|
#лучший вариант kpp\app\ml\models\kpp\yolo11s 10epochs\myyolo11s.pt
|
||||||
|
yolo_model= os.getenv('YOLO_MODEL')
|
||||||
|
|
||||||
|
token= os.getenv('token')
|
||||||
|
|
||||||
|
ip_addr_web= os.getenv('ip_addr_web')
|
||||||
|
|
||||||
|
# Загрузка 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'^[А-Я][0-9]{3}[А-Я]{2}[0-9]{2,3}$|^[0-9]{3}[А-Я]{2}[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 "", 0
|
||||||
|
|
||||||
|
results = ocr.ocr(plate_region, det=True, rec=True, cls=False)
|
||||||
|
|
||||||
|
if not results or not results[0]:
|
||||||
|
print("❌ Текст не обнаружен")
|
||||||
|
return "", 0
|
||||||
|
texts, confidences = [], []
|
||||||
|
for line in results[0]:
|
||||||
|
if line:
|
||||||
|
text = line[1][0]
|
||||||
|
conf = 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:
|
||||||
|
|
||||||
|
return ""
|
||||||
|
best_idx = np.argmax(confidences)
|
||||||
|
best_text = texts[best_idx]
|
||||||
|
return str(best_text)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Ошибка OCR: {str(e)}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def send_car_data(pts, car: Car, plate: Plate ):
|
||||||
|
|
||||||
|
try:
|
||||||
|
url = f"http://{ip_addr_web}/recieve_data_from_ai"
|
||||||
|
|
||||||
|
car_data = {
|
||||||
|
"coordinates" : [
|
||||||
|
car.x1,
|
||||||
|
car.x2
|
||||||
|
],
|
||||||
|
"widht" : car.width,
|
||||||
|
"hight" : car.height
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
plate_data = {
|
||||||
|
"coordinates" : [
|
||||||
|
plate.x1,
|
||||||
|
plate.x2
|
||||||
|
],
|
||||||
|
"widht" : plate.width,
|
||||||
|
"hight" : plate.height
|
||||||
|
}
|
||||||
|
|
||||||
|
data = {
|
||||||
|
"pts": pts,
|
||||||
|
"plate_number": plate.number,
|
||||||
|
"car": car_data,
|
||||||
|
"plate": plate_data
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = json.dumps(data)
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'{token}',
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
response = requests.request("POST", url, headers=headers, data=payload)
|
||||||
|
|
||||||
|
# для тестирования
|
||||||
|
# response = f"""
|
||||||
|
# POST,
|
||||||
|
# url: {url},
|
||||||
|
# headers: {headers},
|
||||||
|
# data: {[payload]}
|
||||||
|
# """
|
||||||
|
|
||||||
|
return {
|
||||||
|
"POST"
|
||||||
|
"sent_data": data,
|
||||||
|
"response": {
|
||||||
|
"status_code": response.status_code,
|
||||||
|
"text": response.text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
error_msg = f"Ошибка при отправке данных: {str(e)}"
|
||||||
|
print(f"\n❌ {error_msg}")
|
||||||
|
return {
|
||||||
|
"error": error_msg
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
container = av.open(rstp_url)
|
||||||
|
|
||||||
|
video_stream = next(s for s in container.streams if s.type == 'video')
|
||||||
|
plate_text = ""
|
||||||
|
plate = Plate("", 0, 0, 0, 0)
|
||||||
|
car = Car(0,0,0,0)
|
||||||
|
for packet in container.demux(video_stream):
|
||||||
|
for frame in packet.decode():
|
||||||
|
|
||||||
|
img = frame.to_ndarray(format='bgr24')
|
||||||
|
results = model.predict(img)
|
||||||
|
|
||||||
|
pts = frame.pts # PTS в тактах (time_base)
|
||||||
|
|
||||||
|
|
||||||
|
for result in results:
|
||||||
|
|
||||||
|
for box in result.boxes:
|
||||||
|
|
||||||
|
# выводит данные о классе 'plate'
|
||||||
|
if box.cls == 0 and box.conf >= 0.4:
|
||||||
|
x1, y1, x2, y2 = map(int,box.xyxy[0])
|
||||||
|
|
||||||
|
text = paddle_ocr(img, x1, y1, x2, y2)
|
||||||
|
|
||||||
|
plate = Plate(text, x1, y1, x2, y2)
|
||||||
|
|
||||||
|
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
|
||||||
|
|
||||||
|
# выводит данные о классе 'car'
|
||||||
|
elif box.cls == 1 and box.conf >= 0.70:
|
||||||
|
x1, y1, x2, y2 = map(int, box.xyxy[0])
|
||||||
|
car = Car(x1, y1, x2, y2)
|
||||||
|
|
||||||
|
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
|
||||||
|
|
||||||
|
print(send_car_data(pts, car, plate))
|
||||||
|
|
||||||
|
cv2.imshow('frame', img)
|
||||||
|
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
container.close()
|
||||||
|
break
|
||||||
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 132 KiB |
BIN
шлагбаум1.mkv
BIN
шлагбаум1.mkv
Binary file not shown.
Loading…
x
Reference in New Issue
Block a user