202 lines
5.8 KiB
Python
202 lines
5.8 KiB
Python
from ultralytics import YOLO
|
||
from paddleocr import PaddleOCR
|
||
import re
|
||
import os
|
||
from dotenv import load_dotenv
|
||
from data_models import Car, Plate, BaseData
|
||
from line_profiler import profile
|
||
import onnxruntime as ort
|
||
import numpy as np
|
||
import cv2
|
||
import torch
|
||
from typing import List, Tuple
|
||
|
||
load_dotenv()
|
||
|
||
#лучший вариант kpp\app\ml\models\kpp\yolo11s 10epochs\myyolo11s.pt
|
||
path = os.getenv('YOLO_MODEL', r'ml/models/kpp/yolo11n_10_epochs/yolo11n_10epochs.pt')
|
||
session = ort.InferenceSession(path, providers=['CPUExecutionProvider'])
|
||
|
||
# Загрузка YOLO-модели
|
||
# model = YOLO(yolo_model)
|
||
|
||
# Инициализация PaddleOCR
|
||
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
|
||
|
||
classNames = ["car", "plate"]
|
||
|
||
input_name = session.get_inputs()[0].name
|
||
input_shape = session.get_inputs()[0].shape # [1, 3, 640, 640]
|
||
INPUT_H, INPUT_W = input_shape[2], input_shape[3]
|
||
|
||
|
||
def nms_numpy(boxes, scores, iou_threshold):
|
||
x1 = boxes[:, 0]
|
||
y1 = boxes[:, 1]
|
||
x2 = boxes[:, 2]
|
||
y2 = boxes[:, 3]
|
||
|
||
areas = (x2 - x1) * (y2 - y1)
|
||
order = scores.argsort()[::-1]
|
||
|
||
keep = []
|
||
while order.size > 0:
|
||
i = order[0]
|
||
keep.append(i)
|
||
xx1 = np.maximum(x1[i], x1[order[1:]])
|
||
yy1 = np.maximum(y1[i], y1[order[1:]])
|
||
xx2 = np.minimum(x2[i], x2[order[1:]])
|
||
yy2 = np.minimum(y2[i], y2[order[1:]])
|
||
|
||
w = np.maximum(0.0, xx2 - xx1)
|
||
h = np.maximum(0.0, yy2 - yy1)
|
||
inter = w * h
|
||
iou = inter / (areas[i] + areas[order[1:]] - inter)
|
||
|
||
inds = np.where(iou <= iou_threshold)[0]
|
||
order = order[inds + 1]
|
||
|
||
return keep
|
||
|
||
def preprocess(frame: np.ndarray) -> np.ndarray:
|
||
img = cv2.resize(frame, (INPUT_W, INPUT_H))
|
||
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
||
img = img.astype(np.float32) / 255.0
|
||
img = np.transpose(img, (2, 0, 1)) # HWC -> CHW
|
||
img = np.expand_dims(img, axis=0) # [1, 3, H, W]
|
||
return img
|
||
|
||
def postprocess(output, conf_thres=0.2, iou_thres=0.4):
|
||
pred = torch.tensor(output[0]) # [1, num_boxes, 6]
|
||
pred = pred[0] # [num_boxes, 6]
|
||
|
||
# Фильтрация по conf
|
||
conf_mask = pred[:, 4] * pred[:, 5] >= conf_thres
|
||
pred = pred[conf_mask]
|
||
|
||
# NMS
|
||
boxes = pred[:, :4]
|
||
scores = pred[:, 4] * pred[:, 5]
|
||
classes = pred[:, 5]
|
||
|
||
boxes_np = boxes.numpy()
|
||
scores_np = scores.numpy()
|
||
nms_idx = nms_numpy(boxes_np, scores_np, iou_thres)
|
||
|
||
pred = pred[nms_idx]
|
||
|
||
return pred.cpu().numpy()
|
||
|
||
|
||
|
||
|
||
@profile
|
||
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 ""
|
||
|
||
|
||
@profile
|
||
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 ""
|
||
|
||
|
||
@profile
|
||
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
|
||
}
|
||
|
||
@profile
|
||
def frame_processed(frame, pts):
|
||
input_tensor = preprocess(frame)
|
||
output = session.run(None, {input_name: input_tensor})
|
||
detections = postprocess(output, conf_thres=0.2)
|
||
|
||
content = []
|
||
numbers = []
|
||
|
||
for det in detections:
|
||
print(det)
|
||
x1, y1, x2, y2, conf, cls = det
|
||
x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
|
||
cls = int(cls)
|
||
|
||
if cls == 0 and conf >= 0.2:
|
||
text = paddle_ocr(frame, x1, y1, x2, y2)
|
||
plate = Plate(text, x1, y1, x2, y2)
|
||
content.append(json_packer(cls, plate))
|
||
numbers.append({'car': text, 'date_in': pts})
|
||
|
||
elif cls == 1 and conf >= 0.5:
|
||
car = Car(x1, y1, x2, y2)
|
||
content.append(json_packer(cls, car))
|
||
|
||
return content, numbers
|
||
|