import cv2
import os
import numpy as np

# Path folder gambar
image_folder = 'D:/Skripsi/ekstraksi fitur/Mycobacterium Tuberculosis'

# 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)

# Baris citra
row = 1
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, img_bin = cv2.threshold(green, 135, 255, cv2.THRESH_BINARY_INV)
    img_bin = cv2.dilate(img_bin, None, iterations=1)

    # Labeling objek
    num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img_bin, connectivity=8)

    # Inisialisasi mask kosong
    mask = np.zeros_like(img_bin)

    # Ukuran minimum dan maksimum objek yang ingin dipertahankan
    min_size = 50
    max_size = 400

    # Iterasi melalui semua objek dan hanya pertahankan yang ukurannya di antara min_size dan max_size
    for j in range(1, num_labels):  # Mulai dari 1 untuk melewatkan background
        if min_size <= stats[j, cv2.CC_STAT_AREA] <= max_size:
            mask[labels == j] = 255

    # Display hasilnya
    cv2.imshow("Original", img_bin)
    cv2.waitKey(800)
    cv2.imshow("Filtered", mask)
    cv2.waitKey(800)
    cv2.destroyAllWindows()