如何使用keras中的ImageDataGenerator和flow_from_directory保存已调整大小的图像

时间:2017-12-15 06:09:47

标签: keras keras-2

我正在使用以下代码调整存储在文件夹(两个类)中的RGB图像:

1/
 1_1/
     img1.jpg
     img2.jpg
     ........
 1_2/
     IMG1.jpg
     IMG2.jpg
     ........
resized/
        1_1/ (here i want to save resized images of 1_1)
        2_2/ (here i want to save resized images of 1_2)

我的数据树如下:

Found 271 images belonging to 2 classes.
Out[12]: <keras.preprocessing.image.DirectoryIterator at 0x7f22a3569400>

运行代码后,我得到的是输出,但不是图像:

String bob2 = "3"; 
System.out.println((int)bob2);

如何保存图片?

6 个答案:

答案 0 :(得分:3)

这里有一个非常简单的版本,可以在任意位置保存一个图像的增强图像:

步骤1。初始化图像数据生成器

在这里我们弄清楚我们要对原始图像进行哪些更改并生成增强后的图像
您可以在此处了解差异效果-https://keras.io/preprocessing/image/

datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1, 
height_shift_range=0.1,shear_range=0.15, 
zoom_range=0.1,channel_shift_range = 10, horizontal_flip=True)

步骤2:在这里,我们选择原始图像对图像进行增强

读入图像

image_path = 'C:/Users/Darshil/gitly/Deep-Learning/My 
Projects/CNN_Keras/test_augment/caty.jpg'

image = np.expand_dims(ndimage.imread(image_path), 0)

第3步:选择要保存增强图像的位置

save_here = 'C:/Users/Darshil/gitly/Deep-Learning/My 
Projects/CNN_Keras/test_augment'

步骤4。我们拟合原始图像

datagen.fit(image)

第5步:遍历图像并使用“ save_to_dir”参数保存

for x, val in zip(datagen.flow(image,                    #image we chose
        save_to_dir=save_here,     #this is where we figure out where to save
         save_prefix='aug',        # it will save the images as 'aug_0912' some number for every new augmented image
        save_format='png'),range(10)) :     # here we define a range because we want 10 augmented images otherwise it will keep looping forever I think
pass

答案 1 :(得分:3)

它只是一个声明,您必须使用该生成器,例如columns.ForeignKey(c => c.CountryID, (SelectList)ViewBag.Countries).Title("Select Country");

.next()

然后您将在from keras.preprocessing.image import ImageDataGenerator dataset=ImageDataGenerator() image = dataset.flow_from_directory('/home/1',target_size=(50,50),save_to_dir='/home/resized',class_mode='binary',save_prefix='N',save_format='jpeg',batch_size=10) image.next() 中看到图像

答案 2 :(得分:2)

this.setState({isLoading:true});方法为您提供了一个&#34;迭代器&#34;,如输出中所述。迭代器本身并没有真正做任何事情。它正在等待迭代,只有这样才能读取和生成实际数据。

Keras中用于拟合的迭代器就像这样使用:

flow_from_directory

通常,您只需将生成器传递给generator = dataset.flow_from_directory('/home/1',target_size=(50,50),save_to_dir='/home/resized',class_mode='binary',save_prefix='N',save_format='jpeg',batch_size=10) for inputs,outputs in generator: #do things with each batch of inputs and ouptus 方法,而不是执行上面的循环。没有必要进行for循环:

fit_generator

Keras只会在通过迭代生成器重新加载和增强后保存图像。

答案 3 :(得分:1)

您可以尝试这个简单的代码示例并根据需要进行修改:

(它根据您的数据生成增强图像,然后将它们保存到不同的文件夹中)

from keras.preprocessing.image import ImageDataGenerator


data_dir = 'data/train' #Due to the structure of ImageDataGenerator, you need to have another folder under train contains your data, for example: data/train/faces
save_dir = 'data/resized'


datagen = ImageDataGenerator(rescale=1./255)


resized = datagen.flow_from_directory(data_dir, target_size=(224, 224),
                                save_to_dir=save_dir,
                                color_mode="rgb", # Choose color mode
                                class_mode='categorical',
                                shuffle=True,
                                save_prefix='N',
                                save_format='jpg', # Formate
                                batch_size=1)


for in in range(len(resized)):
    resized.next()

答案 4 :(得分:0)

如果要将图像保存在与标签同名的文件夹下,则可以在标签列表上循环并在循环内调用扩充代码。

module.exports = {
  webpackFinal: async (config) => {
    const svelteLoader = config.module.rules.find( (r) => r.loader && r.loader.includes('svelte-loader'))
    svelteLoader.options.preprocess = require('svelte-preprocess')()
    return config
  },
  "stories": [
    // "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  "addons": [
    "@storybook/addon-links",
    { name: "@storybook/addon-essentials", options: { docs: false } }
  ]
}

那么当生成器可以直接传递给模型时为什么这样做呢?如果您想使用__.stories.mdx,它不接受生成器,而是接受每个标签在文件夹下的标签数据:

from tensorflow.keras.preprocessing.image import ImageDataGenerator  

# Augmentation + save augmented images under augmented folder

IMAGE_SIZE = 224
BATCH_SIZE = 500
LABELS = ['lbl_a','lbl_b','lbl_c']

for label in LABELS:
  datagen_kwargs = dict(rescale=1./255)  
  dataflow_kwargs = dict(target_size=(IMAGE_SIZE, IMAGE_SIZE), 
                        batch_size=BATCH_SIZE, interpolation="bilinear")

  train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    rotation_range=40,
    horizontal_flip=True,
    width_shift_range=0.1, height_shift_range=0.1,
    shear_range=0.1, zoom_range=0.1,
    **datagen_kwargs)

  train_generator = train_datagen.flow_from_directory(
      'original_images', subset="training", shuffle=True, save_to_dir='aug_images/'+label, save_prefix='aug', classes=[label], **dataflow_kwargs)
  
  # Following line triggers execution of train_generator
  batch = next(train_generator) 

结果

tflite-model-maker

注意:您需要确保文件夹已经存在。

答案 5 :(得分:0)

datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
                     rotation_range =15, 
                     width_shift_range = 0.2, 
                     height_shift_range = 0.2, 
                     shear_range=0.2, 
                     zoom_range=0.2, 
                     horizontal_flip = True, 
                     fill_mode = 'nearest', 
                     brightness_range=[0.5, 1.5])
DATA_DIR = 'splited/train/'
save_here = 'aug dataset/train/normal2/'

cancer = os.listdir(DATA_DIR + 'cancer/')
for i, image_name in enumerate(cancer):
    try:
        if (image_name.split('.')[1] == 'png'):
            image = np.expand_dims(cv2.imread(DATA_DIR +'classs 1/' + image_name), 0)
            for x, val in zip(datagen.flow(image, #image we chose save_to_dir=save_here,     #this is where we figure out where to save
                save_prefix='aug',        # it will save the images as 'aug_0912' some number for every new augmented image
                save_format='png'),range(10)) :     # here we define a range because we want 10 augmented images otherwise it will keep looping forever I think
                    pass
    except Exception:
        print("Could not read image {} with name {}".format(i, image_name))
相关问题