Th-Slip-OCR-K / scan_slip_final.py
Pondet's picture
Example file
da82cc1 verified
import cv2
import easyocr # <--- พระเอกคนใหม่
from ultralytics import YOLO
import numpy as np
# ================= CONFIG =================
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) # gpu=True จะใช้ M4 ช่วยประมวลผล
def clean_amount(text):
"""ล้างขยะยอดเงิน และแปลง O, o ให้เป็น 0"""
# 1. แปลงโอให้เป็นศูนย์ก่อน
text = text.replace('O', '0').replace('o', '0')
# 2. เอาเฉพาะตัวเลข จุด และลูกน้ำ
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]
# Crop ภาพ
x1, y1, x2, y2 = map(int, box.xyxy[0])
h, w, _ = image.shape
# ✅ สูตรขยายกล่อง (Padding)
# เพิ่มขอบซ้ายขวาบนล่างอีก 10 pixel เพื่อกันตัวเลขแหว่ง
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]
# EasyOCR อ่านได้เลย ไม่ต้องทำขาวดำยุ่งยาก
try:
# detail=0 คือเอาแต่ตัวหนังสือ ไม่เอาพิกัด
text_list = reader.readtext(crop_img, detail=0)
text = " ".join(text_list).strip() # ต่อคำเข้าด้วยกัน
# Logic เดิม
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()