我正在对493个类别应用增强,每个类别具有1或2或3或4个图像(未知的1个类别可能只有1个图像,其他可能具有2个图像)。当我使用ImageDataGenerator应用增强时,我得到了增强的图像,但是图像的名称是随机生成的,我希望将放大后的图像名称作为原始图像名称。我尝试了一些代码:
from keras.preprocessing.image import ImageDataGenerator
from keras.applications.inception_v3 import preprocess_input
import glob,os
path = './newaug'
outpath = './newaug_result5/'
filenames = glob.glob(path + "/**/*.png",recursive=True)
imgnum=50
print (filenames)
for img in filenames:
if "DS_Store" in img: continue
src_fname, ext = os.path.splitext(img)
train_datagen=ImageDataGenerator(
preprocessing_function=preprocess_input,
rotation_range = 10,
width_shift_range=0.05,
height_shift_range=0.05,
fill_mode='constant',cval=0.0)
jf_datagen=ImageDataGenerator(
preprocessing_function=preprocess_input
)
img_name = src_fname.split('/')[-1]
new_dir = os.path.join(outpath, src_fname.split('/')[-1].rsplit('-', 1)[0])
if not os.path.lexists(new_dir):
os.mkdir(new_dir)
#save_fname = os.path.join(new_dir, os.path.basename(img_name))
save_fname = new_dir
i=0
train_generator=train_datagen.flow_from_directory(path,target_size=(224,224),
save_to_dir=save_fname)
for batch in train_generator:
i += 1
if i > imgnum:
break
for batch in jf_datagen.flow_from_directory(path,target_size=(224,224),
save_to_dir=save_fname):
i += 1
if i > imgnum:
break
我得到的是图像也属于不同的类别。
classname1/
|-01_133214.png
|-02_43434.png (This image actually belongs to class 2)
classname2/
|-01_13333214.png(This image actually belongs to class 1)
|-02_4343334.png
|-03_13333214.png(This image actually belongs to class 3)
我想要的是,生成与类相同的文件夹,并且增强图像应保存在同一类中,并且名称应与原始图像相同。
classname1/ (Images should belong to same class, for eg 01 signifies classname1)
|classname1-01_2424424.png
|classname1-01_2134242.png
|
|classname1-01_232424.png
classname2/
|classname2-02_323212.png
|classname2-02_321313.png
|
|classname2-02_333339.png
答案 0 :(得分:1)
它使用flow
代替了flow_from_directory
。
代码是:
import numpy as np
import keras,glob,os
import cv2
from keras.preprocessing.image import ImageDataGenerator, array_to_img,img_to_array, load_img
img_path = './newaug'
outpath = './newaug_result7/'
filenames = glob.glob(img_path + "/**/*.png",recursive=True)
for img in filenames:
if "DS_Store" in img: continue
src_fname, ext = os.path.splitext(img)
datagen = ImageDataGenerator(rotation_range = 10,
width_shift_range=0.05,
height_shift_range=0.05,
fill_mode='constant',cval=0.0)
img = load_img(img)
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
img_name = src_fname.split('/')[-1]
new_dir = os.path.join(outpath, src_fname.split('/')[-1].rsplit('-', 1)[0])
if not os.path.lexists(new_dir):
os.mkdir(new_dir)
#save_fname = os.path.join(new_dir, os.path.basename(img_name))
save_fname = new_dir
i = 0
for batch in datagen.flow (x, batch_size=1, save_to_dir = save_fname,
save_prefix = img_name, save_format='jpg'):
i+=1
if i>51:
break