语义分割中用ImageDataGenerator实现数据增强操作之后,可视化增强的图片和标签。
在网上找代码没找到合适的,下面代码为用chatGPT生成的
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
import numpy as np
import matplotlib.pyplot as plt
# 创建一个ImageDataGenerator实例,定义数据增强的参数
datagen = ImageDataGenerator(
rotation_range=0.2, # 随机旋转角度范围
width_shift_range=0.2, # 随机水平位移范围
height_shift_range=0.2, # 随机竖直位移范围
shear_range=0.2, # 随机剪切变换范围
zoom_range=0.2, # 随机缩放范围
horizontal_flip=True, # 水平翻转
fill_mode='nearest') # 填充方式
# 加载一张测试图像和其对应的分割掩膜
img = image.load_img('/kaggle/input/lgg-mri-segmentation/kaggle_3m/TCGA_CS_4941_19960909/TCGA_CS_4941_19960909_15.tif', target_size=(256, 256))
mask = image.load_img('/kaggle/input/lgg-mri-segmentation/kaggle_3m/TCGA_CS_4941_19960909/TCGA_CS_4941_19960909_15_mask.tif', target_size=(256, 256), grayscale=True)
# 将图像和分割掩膜转换为numpy数组
img = image.img_to_array(img)
mask = image.img_to_array(mask)
# 将掩膜的值(0或1)截断为整数
mask = np.round(mask/255.0).astype(int)
# 将图像和掩膜合并成一个4D张量
img_mask = np.concatenate((img, mask), axis=2)
# 将4D张量变形为一个样本的batch,用于后续的数据增强
img_mask = np.expand_dims(img_mask, axis=0)
# 使用datagen对图像和掩膜进行增强
aug_iter = datagen.flow(
img_mask,
batch_size=1,
save_to_dir='/kaggle/working/', # 将增强后的图像保存到这个目录下
save_prefix='aug',
save_format='tif')
# 生成增强后的图像
plt.figure(figsize=(20,10))
# 从aug_iter中获取一个增强后的图像
augmented_img_mask = next(aug_iter)
# 将4D张量变形为图像和掩膜
augmented_img = augmented_img_mask[0,:,:,:3]
augmented_mask = augmented_img_mask[0,:,:,3]
# 可视化增强后的图像和掩膜
plt.subplot(2, 5, i+1)
plt.imshow(augmented_img.astype(np.uint8))
plt.title('Augmented_Image')
plt.subplot(2, 5, i+6)
plt.imshow(augmented_mask.astype(np.uint8),cmap='gray')
plt.title('Augmented_Mask')
plt.tight_layout()
plt.show()