Use python to amplify all pictures in the folder and save them

Deep learning image enhancement

No nonsense, just go to the code

Show some below 内联代码片.

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import tensorflow as tf
import numpy as np
import glob
import os

Big_path = r"D:\ML\images\leaf_enhance\leaf_image_0"  # 原始图片大文件夹路径
Save_path = r"D:\ML\images\leaf_enhance\leaf_image" # 增强图片保存文件夹
generate_num = 25 #单张图片生成新图片的次数
IMAGE_SIZE = (150, 150) # 目标图片保存像素


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')

name_classes = os.listdir(Big_path)
dir_path = glob.glob(os.path.join(Big_path, '*'))  # 存放图片的文件夹路径
dir_path.sort()


for i in range(len(dir_path)):

    print(dir_path[i],'---', name_classes[i])

    os.makedirs(Save_path + '/' + name_classes[i])
    save_path =  Save_path + '/' + name_classes[i]  # 一类增强图片的保存路径

    paths = glob.glob(os.path.join(dir_path[i], '*.jpg'))
    paths.sort()


    num = 0
    for image_path in paths:

        num += 1
        img = load_img(image_path)  # 这是一个PIL图像
        x = np.array(img)  # 把PIL图像转换成一个numpy数组,形状为(3, 150, 150)
        x = tf.image.resize(x,IMAGE_SIZE)
        x = tf.expand_dims(x,0)

        # 下面是生产图片的代码
        # 生产的所有图片保存在 `preview/` 目录下

        i = 0
        for batch in datagen.flow(x, batch_size=1,
                                  save_to_dir=save_path, save_format='jpg'):
            i += 1
            if i > generate_num:
                break  # 否则生成器会退出循环

Use this code to enhance all the images in a folder and save them to a specified directory, and ensure that the small directory name remains unchanged. It can be used for amplification of small data sets.
Insert image description here

Guess you like

Origin blog.csdn.net/YierAnla/article/details/114380367