import json import cv2 import numpy as np import os import itertools from datetime…
- User
import json import cv2 import numpy as np import os import itertools from datetime import datetime from paddleocr import PaddleOCR from ultralytics import YOLO from PyQt5 import QtWidgets, QtGui, QtCore from PyQt5.QtCore import Qt, QThread, pyqtSignal import torch
Kullanılan cihazın adını almak
if torch.cuda.is_available(): gpu_name = torch.cuda.get_device_name(0) print(f"Kullanılan ekran kartı: {gpu_name}") else: print("GPU kullanılmıyor. İşlemci (CPU) kullanılıyor.")
Çakışan KMP Kitaplığı Uyarısını Önlemek İçin
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
'plates' klasörünü oluştur
if not os.path.exists("plates"): os.makedirs("plates")
PaddleOCR ve YOLO modellerini başlat
ocr = PaddleOCR(use_angle_cls=True, use_gpu=True, lang='tr') # Dili ihtiyaca göre değiştirin model = YOLO(r"C:\lpd\Computervisionprojects\ANPR_YOLOv10\weights\best.pt") # YOLO ağırlık yolunu kontrol edin
Karakter değiştirme sözlüğü
char_replacements = { 'O': '0', '0': 'O', 'I': '1', '1': 'I', 'B': '8', '8': 'B', 'Z': '2', '2': 'Z', 'S': '5', '5': 'S', 'G': '6', '6': 'G', 'T': '7', '7': 'T', 'Q': '0', 'D': '0', 'A': '4', '4': 'A', 'V': 'Y', 'Y': 'V', 'L': '4', 'H': 'M', 'M': 'H' }
Blacklist dosyasını yükle
def load_blacklist(): if not os.path.exists('blacklist.txt'): return [] with open('blacklist.txt', 'r') as file: blacklist = [line.strip().upper() for line in file.readlines()] return blacklist
blacklist = load_blacklist()
class VideoThread(QThread): change_pixmap_signal = pyqtSignal(np.ndarray) update_table_signal = pyqtSignal(str, float, str) video_ended_signal = pyqtSignal()
def __init__(self, video_path, brightness=1.0, conf_threshold=0.45, iou_threshold=0.45): super().__init__() self.video_path = video_path self.brightness = brightness self.conf_threshold = conf_threshold self.iou_threshold = iou_threshold self._run_flag = True self.detected_plate_count = 0 self.license_plates = set() self.cache = set() # Önceden tespit edilen plakaları saklamak için self.frame_skip = 1 # Her 2. çerçeveyi işlemek self.current_frame = 0 def run(self): cap = cv2.VideoCapture(self.video_path) while self._run_flag and cap.isOpened(): ret, frame = cap.read() if not ret: self.video_ended_signal.emit() # Video bitince sinyal gönder break self.current_frame += 1 if self.current_frame % self.frame_skip != 0: continue # Çerçeveyi atla # Parlaklık artırma frame = cv2.convertScaleAbs(frame, alpha=self.brightness, beta=0) # Çerçeveyi yeniden boyutlandır resized_frame = cv2.resize(frame, (640, 480)) # YOLO ile plaka tespiti results = model.predict(resized_frame, conf=self.conf_threshold, iou=self.iou_threshold, device=0) # device=0 GPU kullanımı için for result in results: boxes = result.boxes for box in boxes: x1, y1, x2, y2 = map(int, box.xyxy[0]) cv2.rectangle(resized_frame, (x1, y1), (x2, y2), (255, 0, 0), 2) labels = self.run_all_ocr_combinations(resized_frame, x1, y1, x2, y2) if labels: for label, score in labels: formatted_label = self.format_plate(label) if formatted_label and formatted_label not in self.cache: self.detected_plate_count += 1 self.license_plates.add(formatted_label) self.cache.add(formatted_label) # Önbellek boyutunu sınırlayın if len(self.cache) > 500: self.cache.pop() # Plaka görüntüsünü diske kaydet plate_image = resized_frame[y1:y2, x1:x2] image_path = f"plates/plate_{self.detected_plate_count}.png" cv2.imwrite(image_path, plate_image) # GUI'yi güncellemek için sinyalleri yayınla self.update_table_signal.emit(formatted_label, score, image_path) # Çerçeveyi GUI'ye gönder self.change_pixmap_signal.emit(resized_frame) # FPS kontrolü (opsiyonel) self.msleep(30) cap.release() def stop(self): self._run_flag = False self.wait() def run_all_ocr_combinations(self, frame, x1, y1, x2, y2): labels = [] cropped_frame = frame[y1:y2, x1:x2] try: result = ocr.ocr(cropped_frame, rec=True, cls=True) if result: text, score = self.extract_ocr_data(result) if text: labels.append((text, score)) variations = self.get_all_variations(text) for variation in variations: labels.append((variation, score * 0.1)) else: labels.append(("invalid result", 0.0)) else: labels.append(("invalid result", 0.0)) except Exception as e: print(f"OCR Hatası: {e}") labels.append(("invalid result", 0.0)) return labels def extract_ocr_data(self, result): text = "" score = 0.0 try: for line in result: if isinstance(line, list) and len(line) > 0: for word_info in line: if isinstance(word_info, list) and len(word_info) > 1: text += word_info[1][0] + " " score += word_info[1][1] text = text.strip().upper() # Karakter dönüşümlerini uygula text = ''.join([char_replacements.get(c, c) for c in text]) return text, score / len(result) except Exception as e: print(f"OCR Sonuç İşleme Hatası: {e}") return "", 0.0 def get_all_variations(self, text): # Başlangıçta sadece orijinal metni içeren bir liste variations = [text] # Her bir karakter değişimini uygula for original_char, replacement_char in char_replacements.items(): new_variations = set() # Benzersiz yeni varyasyonlar için set kullan for variant in variations: # Her varyasyon için, orijinal karakterin bulunduğu tüm konumlarda değiştirme yap indices = [i for i, char in enumerate(variant) if char == original_char or char == replacement_char] if not indices: # Eğer orijinal veya eşleşen karakter yoksa, varyasyonu olduğu gibi ekle new_variations.add(variant) else: # Tüm olası kombinasyonları oluştur for combo in itertools.product([original_char, replacement_char], repeat=len(indices)): temp = list(variant) for idx, char in zip(indices, combo): temp[idx] = char new_variations.add("".join(temp)) # Mevcut varyasyonlara yeni oluşturulanları ekle variations.extend(new_variations) # Aynı varyasyonları tekrardan önlemek için set kullanarak benzersiz hale getir return list(set(variations)) def format_plate(self, label): # Boşlukları kaldır label = label.replace(" ", "") # Plakanın formatını kontrol et: en az 6 karakter ve ilk iki ile son iki karakter rakam olmalı if len(label) >= 6 and label[:2].isdigit() and label[-2:].isdigit(): return label else: return None - Assistant
Bu tür bir projeyi endüstriyel bir uygulama olarak sunmak ve geniş bir kullanıcı kitlesine dağıtmak istiyorsanız, belirli adımları takip ederek projenizi daha profesyonel ve kullanıma hazır bir hale getirebilirsiniz. İşte bu süreci yolunuza koymanıza yardımcı olacak bazı önemli adımlar ve öneriler: