| import cv2 |
| import easyocr |
| from ultralytics import YOLO |
| import numpy as np |
|
|
| |
| MODEL_PATH = '/Volumes/ShareMac/Th-Slip-OCR-K/runs/detect/train_v4_final/weights/best.pt' |
| IMAGE_PATH = 'E4EBFFEF-EAA7-449A-BA6E-7884FB3211F1.JPG' |
| |
|
|
| |
| print("⏳ Initializing EasyOCR (Thai Engine)...") |
| reader = easyocr.Reader(['th', 'en'], gpu=True) |
|
|
| def clean_amount(text): |
| """ล้างขยะยอดเงิน และแปลง O, o ให้เป็น 0""" |
| |
| text = text.replace('O', '0').replace('o', '0') |
| |
| |
| allowed = "0123456789.," |
| return "".join([c for c in text if c in allowed]) |
|
|
| def clean_accnum(text): |
| allowed = "0123456789-xX" |
| return "".join([c for c in text if c in allowed]) |
|
|
| def run_scanner(): |
| print(f"🔄 Loading YOLO Model...") |
| model = YOLO(MODEL_PATH) |
|
|
| print(f"📸 Scanning: {IMAGE_PATH}") |
| image = cv2.imread(IMAGE_PATH) |
| |
| results = model(IMAGE_PATH, verbose=False) |
| |
| data = {"transaction": "-", "date": "-", "pp1": "-", "accnum": "-", "pp2": "-", "amount": "-"} |
|
|
| print("\n" + "="*50) |
| print(" 🧾 SLIP SCANNER (EasyOCR Edition) ") |
| print("="*50) |
|
|
| for result in results: |
| for box in result.boxes: |
| conf = float(box.conf) |
| if conf < 0.5: continue |
| |
| class_id = int(box.cls) |
| label = model.names[class_id] |
|
|
| |
| x1, y1, x2, y2 = map(int, box.xyxy[0]) |
| h, w, _ = image.shape |
|
|
| |
| |
| padding = 10 |
| x1 = max(0, x1 - padding) |
| y1 = max(0, y1 - padding) |
| x2 = min(w, x2 + padding) |
| y2 = min(h, y2 + padding) |
| crop_img = image[y1:y2, x1:x2] |
|
|
| |
| try: |
| |
| text_list = reader.readtext(crop_img, detail=0) |
| text = " ".join(text_list).strip() |
|
|
| |
| display_label = label |
| if label == 'amount': |
| text = clean_amount(text) |
| display_label = "💰 ยอดเงิน" |
| elif label == 'accnum': |
| text = clean_accnum(text) |
| display_label = "🔢 เลขบัญชี" |
| elif label == 'pp1': |
| display_label = "📤 ผู้โอน" |
| elif label == 'pp2': |
| display_label = "📥 ผู้รับ" |
| elif label == 'transaction': |
| if "โดน" in text: text = text.replace("โดน", "โอน") |
| display_label = "🔄 ประเภท" |
|
|
| data[label] = text |
| print(f"🟢 {display_label:<15}: {text}") |
|
|
| except Exception as e: |
| print(f"⚠️ Error: {e}") |
|
|
| print("-" * 50) |
| |
| print(f"📝 สรุป: {data['transaction']} | {data['amount']} บาท") |
| print(f" จาก: {data['pp1']} ({data['accnum']}) -> ไปยัง: {data['pp2']}") |
| print("=" * 50) |
|
|
| if __name__ == "__main__": |
| run_scanner() |