我将尝试实现Keras自定义图像数据生成器,以便可以进行头发和显微镜图像增强。
这是Datagenerator类:
现在创建DataGenerator对象:
这是Datagenerator类:
class DataGenerator( Sequence ):
def __init__(self,image_paths,labels, augmentations, batch_size=32, image_dimension=(224,224,3), shuffle=False):
self.image_paths = image_paths
self.labels = labels
self.batch_size = batch_size
self.image_dimension = image_dimension
self.shuffle = shuffle
self.augment = augmentations
def __len__(self):
return int(np.ceil(len(self.image_paths) / self.batch_size ))
def _getitem__(self,index):
indexes = self.indexes[index*self.batch_size : (index+1)*self.batch_size]
batch_y = np.array([self.labels[k] for k in indexes])
batch_x = [cv2.cvtColor(cv2.imread(self.image_paths[k]), cv2.COLOR_RGB2BGR) for k in indexes]
return np.stack([
self.augment(image=x)["image"] for x in batch_x
], axis=0), np.array(batch_y)
以下代码是用于 albumentations 增强(只是为了测试数据生成器是否有效而尝试使用 albumentations 增强):
AUGMENTATIONS_TRAIN = Compose([
HorizontalFlip(p=0.5),
RandomContrast(limit=0.2, p=0.5),
RandomGamma(gamma_limit=(80, 120), p=0.5),
RandomBrightness(limit=0.2, p=0.5),
HueSaturationValue(hue_shift_limit=5, sat_shift_limit=20,
val_shift_limit=10, p=.9),
# CLAHE(p=1.0, clip_limit=2.0),
ShiftScaleRotate(
shift_limit=0.0625, scale_limit=0.1,
rotate_limit=15, border_mode=cv2.BORDER_REFLECT_101, p=0.8),
ToFloat(max_value=255)
])
AUGMENTATIONS_TEST = Compose([
# CLAHE(p=1.0, clip_limit=2.0),
ToFloat(max_value=255)
])
现在创建DataGenerator对象:
train_datagen = DataGenerator( train['images'],
train['target'],
augmentations=AUGMENTATIONS_TRAIN,
batch_size=32,
image_dimension=(224,224,3) )
val_datagen = DataGenerator( validation['images'],
validation['target'],
augmentations=AUGMENTATIONS_TEST,
batch_size=16,
image_dimension=(224,224,3) )`
当我运行model.fit_generator(generator=train_datagen,steps_per_epoch=30,epochs = 30,validation_data=val_datagen,validation_steps=15)
时,会出现NonImplementedError错误。
我在这里分享了我的内核,并从这里寻求帮助。我还寻找了其他增强图像的方法,但都是相同的。
如果有人能告诉我问题出在哪里以及如何解决,我将不胜感激。是否有其他更好的方法在Keras中进行自定义图像增强。