import torch
import cv2
import os
import glob
from torch.utils.data import Dataset
import random

class ISBI_Loader(Dataset):
    def __init__(self, data_path):
        # 初始化函數，讀取所有 data_path 下的圖片
        self.data_path = data_path
        self.imgs_path = glob.glob(os.path.join(data_path, 'Training_Images/*.png'))

    def augment(self, image, flipCode):
        # 使用 cv2.flip 進行數據增強，flipCode 為 1 時水平翻轉，0 垂直翻轉，-1 水平+垂直翻轉
        flip = cv2.flip(image, flipCode)
        return flip
        
    def __getitem__(self, index):
        # 根據 index 讀取圖片
        image_path = self.imgs_path[index]
        # 根據 image_path 生成 label_path
        label_path = image_path.replace('Training_Images', 'Training_Labels')
        #label_path = label_path.replace('.jpg', '.png') # todo 更新標籤文件的邏輯

        # 讀取訓練圖片和標籤圖片
        # print(image_path)
        # print(label_path)
        image = cv2.imread(image_path)
        label = cv2.imread(label_path)
        image = cv2.resize(image, (512,512))
        label = cv2.resize(label, (512,512), interpolation=cv2.INTER_NEAREST)
        # 將數據轉為單通道的圖片
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        label = cv2.cvtColor(label, cv2.COLOR_BGR2GRAY)
       
        if label.max() > 1:
            label = label / 255
        # 隨機進行數據增強，為 2 時不做處理
        flipCode = random.choice([-1, 0, 1, 2,])
        if flipCode != 2:
            image = self.augment(image, flipCode)
            label = self.augment(label, flipCode)
        image = image.reshape(1, image.shape[0], image.shape[1])
        label = label.reshape(1, label.shape[0], label.shape[1])
        return image, label

    def __len__(self):
        # 返回訓練集大小
        return len(self.imgs_path)

    
if __name__ == "__main__":
    isbi_dataset = ISBI_Loader("data/train/")
    print("數據個數：", len(isbi_dataset))
    train_loader = torch.utils.data.DataLoader(dataset=isbi_dataset,
                                               batch_size=2,
                                               shuffle=True)
    for image, label in train_loader:
        print(image.shape)
