update
This commit is contained in:
parent
645e561ebf
commit
05ffea3e04
2
.gitignore
vendored
2
.gitignore
vendored
@ -20,7 +20,7 @@ site_build
|
||||
venv
|
||||
docs.zip
|
||||
archive.zip
|
||||
|
||||
.cursor
|
||||
# vim temporary files
|
||||
*~
|
||||
.*.sw?
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 18 KiB |
@ -1,118 +0,0 @@
|
||||
# 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() # Инициализируем таблицы только если подключение успешно
|
||||
@ -1,160 +0,0 @@
|
||||
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
|
||||
@ -8,83 +8,83 @@ 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
|
||||
|
||||
# Инициализируем модель YOLO
|
||||
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)
|
||||
|
||||
# Названия классов
|
||||
className = ["car", "plate"]
|
||||
|
||||
# Инициализируем PaddleOCR с оптимизированными параметрами
|
||||
#Initialize the Paddle OCR
|
||||
ocr = PaddleOCR(use_angle_cls = True, use_gpu = False)
|
||||
# ocr = PaddleOCR(
|
||||
# use_angle_cls=True,
|
||||
# lang='en',
|
||||
# lang='ch', # Используем 'ch' как базовый, но с кастомной моделью для мультиязычности
|
||||
# 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
|
||||
# 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 = 100 # Уменьшаем высоту для лучшего распознавания
|
||||
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 = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
||||
|
||||
# Локальная нормализация с помощью CLAHE
|
||||
clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(8, 8))
|
||||
normalized = clahe.apply(gray)
|
||||
|
||||
|
||||
# Увеличение контраста
|
||||
alpha = 1.3 # Уменьшаем контраст
|
||||
beta = 30 # Увеличиваем яркость
|
||||
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,
|
||||
15, # Уменьшаем размер окна
|
||||
5 # Уменьшаем константу
|
||||
cv2.THRESH_BINARY_INV, # Используем инверсию для темного текста
|
||||
11,
|
||||
2
|
||||
)
|
||||
|
||||
# Морфологические операции
|
||||
kernel = np.ones((2,2), np.uint8)
|
||||
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
|
||||
# Морфологические операции для очистки
|
||||
kernel = np.ones((2, 2), np.uint8)
|
||||
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel, iterations=1)
|
||||
|
||||
# Добавляем белые поля
|
||||
padding = 10
|
||||
padded = cv2.copyMakeBorder(
|
||||
@ -93,12 +93,11 @@ def preprocess_plate_image(plate_img):
|
||||
cv2.BORDER_CONSTANT,
|
||||
value=255
|
||||
)
|
||||
|
||||
# Сохраняем промежуточный результат для отладки
|
||||
|
||||
# Сохраняем для отладки
|
||||
cv2.imwrite('preprocessed_plate.jpg', padded)
|
||||
|
||||
return padded
|
||||
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Ошибка предобработки: {e}")
|
||||
return plate_img
|
||||
@ -106,208 +105,119 @@ def preprocess_plate_image(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
|
||||
|
||||
# Если текст не соответствует ожидаемой структуре, возвращаем пустую строку
|
||||
|
||||
# Удаляем лишние символы, но сохраняем буквы и цифры
|
||||
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))
|
||||
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 ))
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# Предобработка изображения
|
||||
# processed_img = preprocess_plate_image(plate_region)
|
||||
|
||||
# Распознавание текста
|
||||
results = ocr.ocr(processed_img, det=True, rec=True, cls=False)
|
||||
|
||||
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]: # Берем первый результат из списка
|
||||
|
||||
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}%")
|
||||
|
||||
# Очистка и нормализация текста
|
||||
text = line[1][0]
|
||||
conf = float(line[1][1])
|
||||
print(f"Найден текст: {text} (уверенность: {conf*100:.1f}%)")
|
||||
|
||||
cleaned_text = clean_plate_text(text)
|
||||
print(f"Очищенный текст: {cleaned_text}")
|
||||
|
||||
if cleaned_text:
|
||||
texts.append(cleaned_text)
|
||||
confidences.append(conf)
|
||||
print("✅ Текст принят")
|
||||
print(f"Очищенный текст: {cleaned_text}")
|
||||
else:
|
||||
print("❌ Текст отклонен (слишком короткий или пустой)")
|
||||
|
||||
print("❌ Текст отклонен")
|
||||
|
||||
if not texts:
|
||||
print("❌ Нет подходящих вариантов текста")
|
||||
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}%)")
|
||||
|
||||
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)
|
||||
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 JSON File
|
||||
cummulative_file_path = "json/LicensePlateData.json"
|
||||
existing_data = []
|
||||
if os.path.exists(cummulative_file_path):
|
||||
with open(cummulative_file_path, 'r') as f:
|
||||
with open(cummulative_file_path, 'r', encoding='utf-8') 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()
|
||||
|
||||
|
||||
|
||||
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.30) # Снижаем порог детекции
|
||||
|
||||
|
||||
results = model.predict(frame, conf=0.80) # Снижаем порог для лучшей детекции
|
||||
|
||||
for result in results:
|
||||
boxes = result.boxes
|
||||
for box in boxes:
|
||||
@ -315,150 +225,61 @@ def stream(frame):
|
||||
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:
|
||||
|
||||
if className[classNameInt] == "plate" and conf >= 0.50:
|
||||
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))
|
||||
|
||||
# Рисуем рамку по оригинальным координатам
|
||||
print(f"🚗 Номерной знак обнаружен (уверенность: {conf*100:.1f}%)")
|
||||
|
||||
# Рисуем рамку
|
||||
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:
|
||||
|
||||
# Распознаем текст
|
||||
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
|
||||
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 = "ОШИБКА ПРОВЕРКИ"
|
||||
# Здесь должна быть проверка в базе данных
|
||||
# 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("❌ Текст не распознан или низкая уверенность")
|
||||
|
||||
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()
|
||||
return "ОШИБКА ОБРАБОТКИ", ""
|
||||
Loading…
x
Reference in New Issue
Block a user