import cv2
import os
import numpy as np
import xlsxwriter
from skimage.measure import regionprops, label

# Path folder gambar
image_folder = 'D:/Skripsi/ekstraksi fitur/Corynebacterium Diphteriae'

# Cek apakah folder gambar ada
if not os.path.isdir(image_folder):
    print(f"Folder {image_folder} tidak ditemukan.")
    exit()

# Jumlah gambar dalam folder
image_files = [f for f in os.listdir(image_folder) if f.endswith('.jpg')]
num_images = len(image_files)

# Fungsi untuk menghitung eccentricity
def calculate_eccentricity(region):
    if region.minor_axis_length == 0:
        return 0
    else:
        return np.sqrt(1 - (region.minor_axis_length / region.major_axis_length)**2)

# Membuat workbook dan worksheet
output_file = 'D:/Skripsi/ekstraksi fitur/data_fitur.xlsx'
workbook = xlsxwriter.Workbook(output_file)
worksheet = workbook.add_worksheet()

# Menulis header
headers = ['File Name', 'Jumlah Objek', 'Eccentricity Rata-Rata', 'Metric Rata-Rata', 'Mean Hue Rata-Rata', 'Mean Saturation Rata-Rata', 'Mean Value Rata-Rata']
for col, header in enumerate(headers):
    worksheet.write(0, col, header)

row = 1

# Ekstraksi fitur
for i in range(num_images):
    file_name = f'{image_folder}/{image_files[i]}'

    # Preprocessing
    img = cv2.imread(file_name, 1)
    if img is None:
        print(f"Gagal membaca file: {file_name}")
        continue

    blue, green, red = cv2.split(img)

    # Thresholding
    ret, img1 = cv2.threshold(green, 115, 255, cv2.THRESH_BINARY_INV)
    img1 = cv2.dilate(img1.copy(), None, iterations=1)
    img1 = cv2.erode(img1.copy(), None, iterations=4)

    # Labeling
    labeled_img = label(img1)
    regions = regionprops(labeled_img)
    num_objects = len(regions)

    if num_objects == 0:
        continue

    # Inisialisasi variabel untuk agregasi
    total_eccentricity = 0
    total_metric = 0
    total_hue = 0
    total_saturation = 0
    total_value = 0

    for region in regions:
        # Fitur bentuk
        eccentricity = calculate_eccentricity(region)
        area = region.area
        perimeter = region.perimeter
        metric = (4 * np.pi * area) / (perimeter ** 2) if perimeter != 0 else 0

        # Fitur warna HSV
        mask = np.zeros(img.shape[:2], dtype="uint8")
        mask[labeled_img == region.label] = 255
        hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mean_val = cv2.mean(hsv_img, mask=mask)[:3]

        # Agregasi fitur
        total_eccentricity += eccentricity
        total_metric += metric
        total_hue += mean_val[0]
        total_saturation += mean_val[1]
        total_value += mean_val[2]

    # Hitung rata-rata
    mean_eccentricity = total_eccentricity / num_objects
    mean_metric = total_metric / num_objects
    mean_hue = total_hue / num_objects
    mean_saturation = total_saturation / num_objects
    mean_value = total_value / num_objects

    # Menulis hasil ke worksheet
    worksheet.write(row, 0, image_files[i])
    worksheet.write(row, 1, num_objects)
    worksheet.write(row, 2, mean_eccentricity)
    worksheet.write(row, 3, mean_metric)
    worksheet.write(row, 4, mean_hue)
    worksheet.write(row, 5, mean_saturation)
    worksheet.write(row, 6, mean_value)

    row += 1

# Menutup workbook
workbook.close()
print(f"Hasil ekstraksi fitur disimpan di {output_file}")
