kpp/app/services/ml/stream.py

285 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 "ОШИБКА ОБРАБОТКИ", ""