import cv2
import numpy as np
import os

def clean_scanned_image(image_path, output_path, block_size=21, C=15):
    """Xử lý làm sạch ảnh scan bằng Adaptive Thresholding"""
    # 1. Đọc ảnh grayscale
    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    if img is None:
        print(f"❌ Không đọc được ảnh: {image_path}")
        return

    h, w = img.shape
    print(f"📐 Ảnh gốc: {w}x{h} px")

    # 2. Bilateral Filter — khử nhiễu hạt, giữ nét chữ
    filtered = cv2.bilateralFilter(img, d=9, sigmaColor=75, sigmaSpace=75)

    # 3. Adaptive Thresholding (Gaussian)
    thresh = cv2.adaptiveThreshold(
        filtered, 255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
        cv2.THRESH_BINARY,
        block_size, C
    )

    # 4. Morphology close — xóa đốm đen nhỏ
    kernel = np.ones((1, 1), np.uint8)
    cleaned = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

    cv2.imwrite(output_path, cleaned)
    print(f"✅ Đã lưu: {output_path}")
    return cleaned

# ===== MAIN =====
base_dir = "/home/tuan-nguyen/.openclaw/workspace/010-pali-thaykha"
input_png = os.path.join(base_dir, "page_14_raw-14.png")

# Thử 3 bộ tham số: mặc định, xóa mờ mạnh hơn, giữ nét nhiều hơn
params = [
    ("cleaned_page14_C15_b21.png", 21, 15, "Mặc định (C=15, block=21)"),
    ("cleaned_page14_C22_b21.png", 21, 22, "Xóa mờ mạnh (C=22, block=21)"),
    ("cleaned_page14_C12_b25.png", 25, 12, "Giữ nét (C=12, block=25)"),
    ("cleaned_page14_C18_b17.png", 17, 18, "Trung bình hẹp (C=18, block=17)"),
]

for fname, bs, c, desc in params:
    out = os.path.join(base_dir, fname)
    print(f"\n🔧 {desc}")
    clean_scanned_image(input_png, out, block_size=bs, C=c)
