You need to enable JavaScript to run this app. 如何为图像分割模型创建适配Drishti_GS数据集的data generator
优惠活动
大模型
产品
解决方案
定价
更多

如何为图像分割模型创建适配Drishti_GS数据集的data generator

数据集加载与Data Generator实现方案

路径配对实现

先通过文件名特征匹配原始图、视杯标注、视盘标注的对应关系,避免加载时样本错乱:

import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split

# 分别存储三类文件的路径
img_paths = []
cup_label_paths = []
disc_label_paths = []

for root, dirs, files in os.walk("."):
    for filename in files:
        if not filename.endswith(".png"):
            continue
        full_path = os.path.join(root, filename)
        # 按照Drishti_GS数据集的命名规则分类
        if "cupSoftMap" in filename:
            cup_label_paths.append(full_path)
        elif "discSoftMap" in filename:
            disc_label_paths.append(full_path)
        else:
            img_paths.append(full_path)

# 按样本ID排序,保证三类文件顺序一一对应
img_paths.sort(key=lambda x: os.path.basename(x).split(".")[0])
cup_label_paths.sort(key=lambda x: os.path.basename(x).split("_cupSoftMap")[0])
disc_label_paths.sort(key=lambda x: os.path.basename(x).split("_discSoftMap")[0])

# 拆分训练集、验证集,拆分比例可自行调整
train_img, val_img, train_cup, val_cup, train_disc, val_disc = train_test_split(
    img_paths, cup_label_paths, disc_label_paths, test_size=0.2, random_state=42
)

主流框架可用的Data Generator实现

1. PyTorch版本 Dataset + DataLoader

适配PyTorch生态,支持自定义数据增强、多进程加载:

from torch.utils.data import Dataset, DataLoader

class DrishtiGSDataset(Dataset):
    def __init__(self, img_paths, cup_paths, disc_paths, img_size=(512,512), augment_pipeline=None):
        self.img_paths = img_paths
        self.cup_paths = cup_paths
        self.disc_paths = disc_paths
        self.img_size = img_size
        self.augment = augment_pipeline

    def __len__(self):
        return len(self.img_paths)

    def __getitem__(self, idx):
        # 加载原始眼底图像
        img = cv2.imread(self.img_paths[idx])
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = cv2.resize(img, self.img_size) / 255.0

        # 加载视杯soft标注
        cup = cv2.imread(self.cup_paths[idx], 0)
        cup = cv2.resize(cup, self.img_size) / 255.0

        # 加载视盘soft标注
        disc = cv2.imread(self.disc_paths[idx], 0)
        disc = cv2.resize(disc, self.img_size) / 255.0

        # 执行数据增强(同步处理图像和掩码)
        if self.augment:
            aug_res = self.augment(image=img, masks=[cup, disc])
            img = aug_res['image']
            cup, disc = aug_res['masks']

        # 转为PyTorch要求的CHW格式
        img = img.transpose(2,0,1).astype(np.float32)
        cup = np.expand_dims(cup, 0).astype(np.float32)
        disc = np.expand_dims(disc, 0).astype(np.float32)

        return img, cup, disc

# 实例化加载器
train_dataset = DrishtiGSDataset(train_img, train_cup, train_disc)
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=4)

val_dataset = DrishtiGSDataset(val_img, val_cup, val_disc)
val_loader = DataLoader(val_dataset, batch_size=8, shuffle=False, num_workers=4)

2. TensorFlow/Keras版本 Sequence生成器

适配TensorFlow生态,避免动态图模式下生成器数据泄漏问题:

import tensorflow as tf

class DrishtiGSGenerator(tf.keras.utils.Sequence):
    def __init__(self, img_paths, cup_paths, disc_paths, batch_size=8, img_size=(512,512), shuffle=True):
        self.img_paths = img_paths
        self.cup_paths = cup_paths
        self.disc_paths = disc_paths
        self.batch_size = batch_size
        self.img_size = img_size
        self.shuffle = shuffle
        self.on_epoch_end()

    def __len__(self):
        return int(np.floor(len(self.img_paths) / self.batch_size))

    def on_epoch_end(self):
        self.indexes = np.arange(len(self.img_paths))
        if self.shuffle:
            np.random.shuffle(self.indexes)

    def __getitem__(self, index):
        indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
        batch_img, batch_cup, batch_disc = [], [], []

        for i in indexes:
            # 加载原始图像
            img = tf.keras.preprocessing.image.load_img(self.img_paths[i], target_size=self.img_size)
            img = tf.keras.preprocessing.image.img_to_array(img) / 255.0
            # 加载视杯标注
            cup = tf.keras.preprocessing.image.load_img(self.cup_paths[i], target_size=self.img_size, color_mode="grayscale")
            cup = tf.keras.preprocessing.image.img_to_array(cup) / 255.0
            # 加载视盘标注
            disc = tf.keras.preprocessing.image.load_img(self.disc_paths[i], target_size=self.img_size, color_mode="grayscale")
            disc = tf.keras.preprocessing.image.img_to_array(disc) / 255.0

            batch_img.append(img)
            batch_cup.append(cup)
            batch_disc.append(disc)

        return np.array(batch_img), {"cup_output": np.array(batch_cup), "disc_output": np.array(batch_disc)}

# 实例化生成器
train_gen = DrishtiGSGenerator(train_img, train_cup, train_disc, batch_size=8)
val_gen = DrishtiGSGenerator(val_img, val_cup, val_disc, batch_size=8, shuffle=False)

实用提示

  • 分割任务的数据增强推荐使用albumentations库,对图像和掩码的同步增强支持更灵活,比框架自带的增强工具适配性更好
  • 如果需要把soft map转为二分类标注,直接设置阈值(比如0.5)做二值化即可,训练时如果用软标签直接使用原始值即可
  • 路径配对完成后建议打印前3组对应文件名,确认配对无误后再启动训练,避免样本不匹配导致训练失效

内容的提问来源于stack exchange,提问作者user16452440

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 15:03:03