import cv2
import numpy as np
import matplotlib.pyplot as plt

def process_petroglyph(image_path):
    # 1. قراءة الصورة
    img = cv2.imread(image_path)
    if img is None:
        print("خطأ: لم يتم العثور على الصورة. تأكد من مسار واسم الملف.")
        return

    # 2. التحويل إلى تدرج الرمادي (Grayscale)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 3. تطبيق مرشح CLAHE لموازنة إضاءة الصخرة وإبراز التباين المحلي
    clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
    enhanced_gray = clahe.apply(gray)

    # 4. إزالة مسامات الصخرة والتشويش باستخدام التمويه (Gaussian Blur)
    blurred = cv2.GaussianBlur(enhanced_gray, (5, 5), 0)

    # 5. السحر الحقيقي: العتبة التكيفية (Adaptive Thresholding)
    # تعزل النقش عن الصخرة بغض النظر عن اختلاف ظلال الشمس
    thresh = cv2.adaptiveThreshold(
        blurred, 255, 
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 
        cv2.THRESH_BINARY_INV, # عكس الألوان: النقش أبيض والخلفية سوداء
        blockSize=21, # حجم المربع الذي يتم حساب الإضاءة فيه
        C=10 # درجة حساسية العزل (يمكنك تعديلها بين 5 و 15)
    )

    # 6. تنظيف الشوائب المتبقية (Morphological Opening)
    kernel = np.ones((2, 2), np.uint8)
    cleaned_thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)

    # عرض النتائج للمقارنة باستخدام Matplotlib
    plt.figure(figsize=(15, 5))

    plt.subplot(1, 3, 1)
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.title("الصورة الأصلية")
    plt.axis('off')

    plt.subplot(1, 3, 2)
    plt.imshow(enhanced_gray, cmap='gray')
    plt.title("بعد موازنة الإضاءة (CLAHE)")
    plt.axis('off')

    plt.subplot(1, 3, 3)
    plt.imshow(cleaned_thresh, cmap='gray')
    plt.title("النتيجة النهائية (عزل تكيفي)")
    plt.axis('off')

    plt.tight_layout()
    plt.show()

# قم بتغيير 'rock.jpg' إلى اسم صورتك
process_petroglyph('rock.jpg')
