tensorflow2.0 做数据增强

使用tf2.0做数据增强:
对图片进行反转、旋转等操作。

代码:
需要库

from keras.preprocessing.image import ImageDataGenerator,load_img,img_to_array
import os

此函数执行数据增强功能,前两个参数是需要被做数据增强的两个文件夹地址,后两个参数是做完数据增强后保存图片的地址。

def DataInc(path_cat, path_tiger,to_path_cat, to_path_tiger): 
    #定义图片生成器
    data_gen = ImageDataGenerator(rotation_range=40,
                                  width_shift_range=0.2,
                                  height_shift_range=0.2,
                                  horizontal_flip=True,
                                  vertical_flip=True,
                                  fill_mode='nearest',
                                  data_format='channels_last')
    imgs_cat = os.listdir(path_cat)
    imgs_tiger = os.listdir(path_tiger)
    for img_cat in imgs_cat:
        try:
            img=load_img(path_cat+'\\'+img_cat)
            x = img_to_array(img,data_format="channels_last")   #图片转化成array类型,因flow()接收numpy数组为参数
            x=x.reshape((1,) + x.shape)     #要求为4维

            #使用for循环迭代,生成图片
            i = 0
            for batch in data_gen.flow(x,batch_size=1,
                                       save_to_dir=to_path_cat,
                                       save_prefix='cat',
                                       save_format='jpeg'):
                i += 1
                if i>15:
                    break
        except:
            print('555...Error!')
    for img_tiger in imgs_tiger:
        try:
            img=load_img(path_tiger+'\\'+img_tiger)
            x = img_to_array(img,data_format="channels_last")   #图片转化成array类型,因flow()接收numpy数组为参数
            x=x.reshape((1,) + x.shape)     #要求为4维

            #使用for循环迭代,生成图片
            i = 0
            for batch in data_gen.flow(x,batch_size=1,
                                       save_to_dir=to_path_tiger,
                                       save_prefix='tiger',
                                       save_format='jpeg'):
                i += 1
                if i>20:
                    break
        except:
            print('555...Error!')

执行如下:

path_cat = 'E:\\Machine Learning\\data\\CatAndTiger\\cat'
path_tiger = 'E:\\Machine Learning\\data\\CatAndTiger\\tiger'
to_path_cat = 'E:\\Machine Learning\\data\\CatAndTiger\\cat_inc'
to_path_tiger = 'E:\\Machine Learning\\data\\CatAndTiger\\tiger_inc'
DataInc(path_cat, path_tiger,to_path_cat, to_path_tiger)
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SinHao22

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值