利用keras进行样本扩充

1.首先安装tensorflow和keras(建议通过conda进行安装),网上有好多教程,以下面的教程为例

http://www.linuxidc.com/Linux/2016-07/133214.htm

2.将要扩充的样本放在data目录下的train文件夹下,并在data文件夹下新建一个preview的文件夹用来存放扩充后的样本,具体目录如下:

 test/data/preview <and> train

train目录下为需要扩充的样本文件夹:如bus,flower,horse等等

3.其具体代码如下,只有30多行

empty#-*- coding:utf-8 -*-
import os
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')
def expand(lable):
	j = 1
	if not os.path.isdir('/home/wyq/test/data/preview/'+lable): #判断preview目录下是否存在××该文件夹,
		os.mkdir('/home/wyq/test/data/preview/'+lable) #若不存在则创建一个文件夹来保存扩充后的样本
	for file_name in os.listdir('/home/wyq/test/data/train/'+lable): #要扩充的图片所在目录
		img = load_img('/home/wyq/test/data/train/'+lable+'/'+file_name) #this is a PIL image
		x = img_to_array(img)  # this is a Numpy array with shape (3,150,150)
		x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1,3,150,150)
		
		i = 1
		for batch in datagen.flow(x, batch_size=1,
					 save_to_dir='/home/wyq/test/data/preview/'+lable, save_prefix=lable, save_format='jpg'):#设置扩充后的样本保存位置及属性
			i += 1
			if i > 10:  #每张图片扩充10张
				break  # otherwise the generator would loop indefinitely
		j +=1
		if j>100: #每个文件夹中有100张图片,故遍历100次
			break

expand("bus")# bus为车的图片的文件夹名称
expand("dinosaur")#dinosaur为恐龙图片的文件夹名称
expand("elephant")#同上
expand("flower")#同上
expand("horse")#同上


  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值