基于训练与验证分割文本文件构建tf.keras.preprocessing.image.ImageDataGenerator的实现方法咨询
基于自定义分割文件构建Keras图像生成器
没问题,我来给你梳理下怎么用tf.keras.preprocessing.image.ImageDataGenerator配合自定义的训练/验证分割文件来构建数据生成器,核心就是用flow_from_dataframe方法,具体步骤和代码示例如下:
1. 准备数据:将分割文件转换成DataFrame
首先需要把两个文本文件(每行是图像文件名/路径)转换成Pandas DataFrame,同时提取每个图像对应的标签(假设你的图像还是按类别存放在独立文件夹里,比如路径格式是class_name/image.jpg,可以从路径中直接提取标签)。
示例代码:
import pandas as pd from pathlib import Path import tensorflow as tf # 配置路径 DATA_ROOT = Path("/your/image/root/directory") # 图像根目录 TRAIN_SPLIT_FILE = "/path/to/train_files.txt" # 训练分割文件路径 VAL_SPLIT_FILE = "/path/to/val_files.txt" # 验证分割文件路径 IMAGE_SHAPE = (224, 224) # 你的目标图像尺寸 def create_dataframe(split_file): # 读取分割文件,获取所有图像路径 with open(split_file, "r") as f: img_paths = [line.strip() for line in f if line.strip()] # 从路径中提取类别标签(假设路径最后一级文件夹是类别) labels = [Path(path).parent.name for path in img_paths] # 构建包含图像路径和标签的DataFrame return pd.DataFrame({ "image_path": img_paths, "label": labels }) # 生成训练和验证集的DataFrame train_df = create_dataframe(TRAIN_SPLIT_FILE) val_df = create_dataframe(VAL_SPLIT_FILE)
如果你的分割文件里每行同时包含图像路径和标签(比如class_name/image.jpg cat),可以修改create_dataframe函数,按分隔符拆分每行:
def create_dataframe_with_labels(split_file): img_paths = [] labels = [] with open(split_file, "r") as f: for line in f: line = line.strip() if not line: continue path, label = line.split() # 按空格拆分,根据实际分隔符调整 img_paths.append(path) labels.append(label) return pd.DataFrame({ "image_path": img_paths, "label": labels })
2. 构建数据生成器
接下来初始化ImageDataGenerator,然后用flow_from_dataframe分别构建训练和验证生成器:
# 初始化图像生成器(训练集可以加数据增强,验证集只做归一化) train_datagen = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1./255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, horizontal_flip=True ) val_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255) # 构建训练生成器 train_generator = train_datagen.flow_from_dataframe( dataframe=train_df, directory=str(DATA_ROOT), # 如果image_path是绝对路径,这里设为None即可 x_col="image_path", # DataFrame中存储图像路径的列名 y_col="label", # DataFrame中存储标签的列名 target_size=IMAGE_SHAPE, class_mode="categorical", # 多分类任务用categorical,二分类用binary shuffle=True, batch_size=32 ) # 构建验证生成器 val_generator = val_datagen.flow_from_dataframe( dataframe=val_df, directory=str(DATA_ROOT), x_col="image_path", y_col="label", target_size=IMAGE_SHAPE, class_mode="categorical", shuffle=False, # 验证集不需要打乱 batch_size=32 )
关键注意事项
- 如果你的分割文件里存储的是绝对路径,记得把
flow_from_dataframe的directory参数设为None,这样生成器会直接使用x_col里的完整路径。 class_mode参数要根据你的任务调整:多分类用categorical,二分类用binary,如果不需要标签(比如自编码器任务)可以设为None。- 训练集的
ImageDataGenerator可以添加各种数据增强参数,提升模型泛化能力,验证集一般只做归一化处理,不要加数据增强。
内容的提问来源于stack exchange,提问作者Jürgen K.
相关产品推荐
相关产品推荐

