import Augmentor
import glob
import os
import random
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
train_path = '/home/csj/task/task1/ori_images' # 原图路径
groud_truth_path = '/home/csj/task/task1/ori_masks' # 标签路径
img_type = 'jpg'
# 原图和标签须保持名称和后缀一致(不一致情况以后再说)
train_tmp_path = '/home/csj/task/task1/new_train33' # 原图增强路径
mask_tmp_path = '/home/csj/task/task1/new_label33' # 标签增强路径
def start(train_path,groud_truth_path):
train_img = glob.glob(train_path+'/*.'+img_type)
masks = glob.glob(groud_truth_path+'/*.'+img_type)
if len(train_img) != len(masks):
print ("trains can't match masks")
return 0
for i in range(len(train_img)):
train_img_tmp_path = train_tmp_path
if not os.path.lexists(train_img_tmp_path):
os.mkdir(train_img_tmp_path)
img = load_img(train_img[i])
x_t = img_to_array(img)
img_tmp = array_to_img(x_t)
img_tmp.save(train_img_tmp_path+'/'+str(i)+'.'+img_type)
mask_img_tmp_path =mask_tmp_path
if not os.path.lexists(mask_img_tmp_path):
os.mkdir(mask_img_tmp_path)
mask = load_img(masks[i])
x_l = img_to_array(mask)
mask_tmp = array_to_img(x_l)
mask_tmp.save(mask_img_tmp_path+'/'+str(i)+'.'+img_type)
print ("%s folder has been created!"%str(i))
return i+1
def doAugment(num):
sum = 0
for i in range(num):
p = Augmentor.Pipeline(train_tmp_path)
p.ground_truth(mask_tmp_path)
p.rotate(probability=0.5, max_left_rotation=5, max_right_rotation=5)#旋转
p.flip_left_right(probability=0.5)#按概率左右翻转
p.zoom_random(probability=0.6, percentage_area=0.99)#随即将一定比例面积的图形放大至全图
p.flip_top_bottom(probability=0.6)#按概率随即上下翻转
#p.random_distortion(probability=0.8,grid_width=10,grid_height=10, magnitude=20)#小块变形
count = random.randint(40, 60)
print("\nNo.%s data is being augmented and %s data will be created"%(i,count))
sum = sum + count
p.sample(count)
print("Done")
print("%s pairs of data has been created totally"%sum)
a = start(train_path, groud_truth_path)
doAugment(a)
借鉴自添加链接描述
一、所需环境
tensorflow-gpu==1.13
二、调试时报错
1.AttributeError
File “g://VOC2007/data_aug.py", line 5, in
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
File "C:\Users*\Anaconda3\envs\tf_gpu\lib\site-packages\keras_init_.py”, line 5, in
from . import applications
File “C:***\studio\Anaconda3\envs\tf_gpu\lib\site-packages\keras\applications_init_.py”, line 13, in
keras_applications.set_keras_submodules(
AttributeError: module ‘keras_applications’ has no attribute ‘set_keras_submodules’
使用命令pip install keras-models,问题解决
2.MemoryError
跑了一半报错,我看看代码的
把count改小点,太大的话内存就炸了,比如改成
count = random.randint(20, 40)
根据需要自己定
三、批量修改文件名称
生成的文件存在“原图增强路径下的output文件夹”中,首先将文件分类,原图和标签图分开
以原图为例,
1.全选所有图片,shift+鼠标右键,选复制为路径
到excel里粘贴
2.把多余的路径删掉,只留下文件名,然后在c列重新定义文件名为1.jpg,双击这个单元格,使得所有的文件名升序命名,如何在d1中输入公式,=“ren “&A1&” “&C1&””,注意ren后面有一个空格,第二对双引号中间也有一个空格!!!
3.复制d列内容,到原图的文件夹下新建文本文件,将内容粘贴进去,保存,然后把后缀名改成bat,最后双击,搞定