语义分割的data augmentation,keras bug

这几天在做语义分割,由于要做数据增强,便想到了利用keras 的ImageDataGenerator,但是发现在保存mask的时候mask的像素值会默认放大到255。

网上查了很多也没查到,于是去看源码,发现在image.py里, NumpyArrayIterator这个类里面,

    def _get_batches_of_transformed_samples(self, index_array):
        batch_x = np.zeros(tuple([len(index_array)] + list(self.x.shape)[1:]),
                           dtype=K.floatx())
        for i, j in enumerate(index_array):
            x = self.x[j]
            x = self.image_data_generator.random_transform(x.astype(K.floatx()))
            x = self.image_data_generator.standardize(x)
            batch_x[i] = x
        if self.save_to_dir:
            for i, j in enumerate(index_array):
                img = array_to_img(batch_x[i], self.data_format, scale=True)
                fname = '{prefix}_{index}_{hash}.{format}'.format(prefix=self.save_prefix,
                                                                  index=j,
                                                                  hash=np.random.randint(1e4),
                                                                  format=self.save_format)
                img.save(os.path.join(self.save_to_dir, fname))

array_to_img这里默认缩放了。。。

于是把scale改成False就解决了

下面是image和mask增强的代码


from keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.1,
        height_shift_range=0.1,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        vertical_flip=True,
        fill_mode='constant',
        cval=0,)
seed = 1
train_images_generator = train_datagen.flow_from_directory(
        './data_raw/argfile',
        target_size=(540, 960),
        batch_size=1,
        color_mode="rgb",
        class_mode=None,
        save_to_dir='data_arg/55',
        save_format='png',
        seed=seed,
        shuffle=True)
train_masks_generator = train_datagen.flow_from_directory(
         './data_label/argfile',

        target_size=(540, 960),
        batch_size=1,
        color_mode="grayscale",
        class_mode=None,
        save_to_dir='mask_arg/55',
        save_format='png',
        seed=seed,
        shuffle=True)

i = 0
for batch in train_images_generator:
    i += 1    
    if i > 69:
        break  # otherwise the generator would loop indefinitely
    if i == 1:
        print(batch.shape)  # this is a Numpy array with shape (1, 224, 224, 3)
        
i = 0
for batch in train_masks_generator:
    i += 1
    if i > 69:
        break  # otherwise the generator would loop indefinitely 
    if i == 1:
        print(batch.shape)  # this is a Numpy array with shape (1, 224, 224, 1)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值