import os
import cv2
import numpy as np
import pandas as pd
from skimage.feature import graycomatrix, graycoprops

def extract_rgb_features(image):
    """Ekstraksi fitur warna RGB"""
    mean_r = np.mean(image[:, :, 2])
    mean_g = np.mean(image[:, :, 1])
    mean_b = np.mean(image[:, :, 0])
    return mean_r, mean_g, mean_b

def extract_glcm_features(image, distances=[1], angles=[0], levels=256, symmetric=True, normed=True):
    """Ekstraksi fitur tekstur menggunakan GLCM"""
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    glcm = graycomatrix(gray_image, distances, angles, levels=levels, symmetric=symmetric, normed=normed)
    contrast = graycoprops(glcm, 'contrast')[0, 0]
    homogeneity = graycoprops(glcm, 'homogeneity')[0, 0]
    energy = graycoprops(glcm, 'energy')[0, 0]
    correlation = graycoprops(glcm, 'correlation')[0, 0]
    return contrast, homogeneity, energy, correlation

def extract_laplacian_features(image):
    """Ekstraksi fitur tepi menggunakan Laplacian"""
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    laplacian = cv2.Laplacian(gray_image, cv2.CV_64F)
    mean_laplacian = np.mean(np.abs(laplacian))
    var_laplacian = np.var(laplacian)
    return mean_laplacian, var_laplacian

def process_folder(folder_path, label):
    """Memproses semua gambar dalam folder tertentu dan mengekstrak fitur"""
    data = []
    file_count = len(os.listdir(folder_path))
    processed_count = 0

    for filename in os.listdir(folder_path):
        if filename.endswith(('.png', '.jpg', '.jpeg')):
            file_path = os.path.join(folder_path, filename)
            image = cv2.imread(file_path)

            if image is None:
                print(f"❌ [SKIP] Tidak dapat membaca file: {file_path}")
                continue  # Lewati gambar yang tidak bisa dibaca

            try:
                rgb_features = extract_rgb_features(image)
                glcm_features = extract_glcm_features(image)
                laplacian_features = extract_laplacian_features(image)
                
                features = rgb_features + glcm_features + laplacian_features + (label,)
                data.append(features)

                processed_count += 1
                print(f"✅ [{processed_count}/{file_count}] Berhasil diproses: {filename}")
            except Exception as e:
                print(f"❌ [ERROR] Gagal memproses {filename}: {e}")

    return data

def main(folder1, folder2, output_excel, output_csv):
    """Fungsi utama untuk ekstraksi fitur dari dua folder gambar"""
    columns = ['Mean_R', 'Mean_G', 'Mean_B', 'Contrast', 'Homogeneity', 'Energy', 'Correlation', 'Mean_Laplacian', 'Var_Laplacian', 'Label']
    
    print("\n📂 Memproses folder Fresh Strawberry...")
    data1 = process_folder(folder1, 2)  # Label 2 untuk Fresh Strawberry
    
    print("\n📂 Memproses folder Rotten Strawberry...")
    data2 = process_folder(folder2, 1)  # Label 1 untuk Rotten Strawberry

    # Gabungkan kedua dataset
    all_data = data1 + data2

    # Konversi ke DataFrame
    df = pd.DataFrame(all_data, columns=columns)

    # Simpan ke file Excel dan CSV
    df.to_excel(output_excel, index=False)
    df.to_csv(output_csv, index=False)

    print(f"\n✅ Data telah disimpan ke: {output_excel} dan {output_csv}")

if __name__ == "__main__":
    # Ganti dengan path folder yang sesuai
    folder1 = r'C:\Users\user\Documents\dataset_stroberi\Stroberi_segar_BG_grayscale'  # Fresh Strawberry
    folder2 = r'C:\Users\user\Documents\dataset_stroberi\Stroberi_busuk_BG_grayscale'  # Rotten Strawberry
    output_excel = 'ekstraksi_citra_strawberry.xlsx'  # Nama file output Excel
    output_csv = 'ekstraksi_citra_strawberry.csv'  # Nama file output CSV

    main(folder1, folder2, output_excel, output_csv)
