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

def extract_rgb_features(image):
    """Ekstraksi fitur warna RGB"""
    mean_r = np.mean(image[:, :, 2])  # Kanal merah
    mean_g = np.mean(image[:, :, 1])  # Kanal hijau
    mean_b = np.mean(image[:, :, 0])  # Kanal biru
    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)  # Konversi ke grayscale
    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)  # Konversi ke grayscale
    laplacian = cv2.Laplacian(gray_image, cv2.CV_64F)
    mean_laplacian = np.mean(np.abs(laplacian))  # Mean absolute value
    var_laplacian = np.var(laplacian)  # Variance
    return mean_laplacian, var_laplacian

def extract_features(image_path):
    """Fungsi utama untuk mengekstrak semua fitur dari satu gambar"""
    image = cv2.imread(image_path)

    if image is None:
        raise ValueError(f"❌ Tidak dapat membaca gambar: {image_path}")

    # Ekstraksi fitur
    rgb_features = extract_rgb_features(image)
    glcm_features = extract_glcm_features(image)
    laplacian_features = extract_laplacian_features(image)

    # Gabungkan semua fitur
    features = rgb_features + glcm_features + laplacian_features
    return features
