TF Keras:ISIC2019数据集图像增强排除NV类并实现实时生成
ISIC 2019数据集实时图像增强与类别平衡问题求助
我正在处理ISIC 2019数据集的图像增强任务,该数据集包含9个类别,其中“NV”类样本占比严重失衡——总25331张图像中,“NV”类就有12876张。因此我计划将“NV”类排除在增强流程之外,后续再把增强后的其余类别图像与未改动的“NV”类图像重新组合。
我需要一个带有训练/验证拆分的ImageDataGenerator对象,以此实现实时(on-the-fly)增强。但查阅资料后发现无法直接合并两个ImageDataGenerator。
我尝试了以下代码,不仅无法实现实时数据生成器,甚至连图像保存功能都失效;另外,保存增强图像会占用大量存储空间(我仅能使用15GB的Google Drive),特此求助。
from keras.preprocessing.image import ImageDataGenerator import os import shutil # 定义数据文件夹 data_directory = "/content/dataset" # ISIC 2019图像路径 target_directory = "/content/dataset_aug" # 已按子文件夹分类的增强图像路径 # 创建dataset_aug文件夹 os.makedirs(target_directory, exist_ok=True) # 类别名称 class_names = ["AK", "BCC", "BKL", "DF", "MEL", "NV", "SCC", "UNK", "VASC"] # 增强参数 datagen_aug = ImageDataGenerator( rescale=1/255., rotation_range=180, width_shift_range=0.1, height_shift_range=0.1, zoom_range=0.1, horizontal_flip=True, vertical_flip=True, fill_mode='nearest' ) # 遍历所有类别执行增强 for class_name in class_names: class_directory = os.path.join(data_directory, class_name) target_class_directory = os.path.join(target_directory, class_name) # 创建目标目录 if not os.path.exists(target_class_directory): os.makedirs(target_class_directory) if class_name == "NV": # 将所有NV类图像原封不动复制到目标目录 image_files = os.listdir(class_directory) for image_file in image_files: source_path = os.path.join(class_directory, image_file) target_path = os.path.join(target_class_directory, image_file) shutil.copy(source_path, target_path) else: # 对其他类别执行增强并保存到对应目标目录 image_generator = datagen_aug.flow_from_directory( class_directory, target_size=(224, 224), batch_size=32, class_mode=None, save_to_dir=target_class_directory, save_prefix='aug_', save_format='png' ) num_augmented_images = 9200 # 每个类别生成的增强图像数量 for i in range(num_augmented_images): batch = next(image_generator) if (i + 1) % 100 == 0: print(f"已为{class_name}类别生成{i+1}张增强图像") print("数据增强完成。")
内容的提问来源于stack exchange,提问作者mongoq
相关产品推荐
相关产品推荐

