将 tensorflow.keras.preprocessing 应用于图像后如何保存输出图像?

How to save output images after applying tensorflow.keras.preprocessing to images?

如何将预处理后的图像(应用 img_height 和 img_width 预处理后)保存在文件夹中供我查看?

这是我对目录中的图像进行预处理的代码。我的模型在这些预处理图像上进行训练。

def evaluate(image):
  batch_size = 32
  img_height = 180
  img_width = 180
  img = keras.preprocessing.image.load_img(
  image,
  target_size=(img_height, img_width),
  interpolation = "bilinear",
  color_mode = 'rgb'
  )

下面的代码有两个函数。 Save_images 函数从 source_dir 中读取图像,对其进行预处理并将它们保存到 save_to_dir。注意:如果您使 save_to_dir 与 source_dir 相同,源目录中的文件将被覆盖。如果 save_to_dir 不存在,则创建它。如果存在,则检查其内容。如果其中有文件,系统会询问您是否要删除文件、停止该功能或继续。 view_images 函数显示 view_dir

中存在的所有图像
import os
import shutil
from PIL import Image
import tensorflow as tf
import matplotlib.pyplot as plt

def save_images(source_dir, save_to_dir, height,width):
    # function reads in image files from source_dir, preprocess the images and saves them to save_to_dir
    if os.path.isdir(save_to_dir)== True: # if the directory exists
        print('directory ', save_to_dir, ' has images in it')
        ans=input('Enter C to continue, D to delete existing files or H to halt')
        if ans == 'd' or ans == 'D':
            shutil.rmtree(save_to_dir)
            os.mkdir(save_to_dir)
        elif ans == 'h' or ans == 'H':
            print ('Execution terminated by user input')
            return        
    else:
        os.mkdir(save_to_dir)
    flist=os.listdir(source_dir)
    for f in flist:
        fpath=os.path.join(source_dir,f)
        img=tf.keras.preprocessing.image.load_img( fpath, target_size=(height, width),
                                                  interpolation = "bilinear",  color_mode = 'rgb')        
        fname=os.path.split(fpath)[1]
        dest_path=os.path.join(save_to_dir, fname)
        img.save(dest_path)
    print(len(flist), ' files were saved to ', save_to_dir)
  
def view_images(view_dir):
    # function displays all images in the view_dir with titles as the filename
    flist=os.listdir(view_dir)    
    fcount=len(flist)    
    rows= fcount//6 + 1    
    plt.figure(figsize=(20,rows*5))
    for i,f in enumerate(flist):        
        fpath=os.path.join(view_dir,f)        
        img=plt.imread(fpath)
        plt.subplot(rows, 6, i + 1)
        plt.title(f, color='yellow', fontsize=16)
        plt.imshow(img)
    plt.show()
# Example of use    
source_dir=r'C:\Temp\butterflies\detector'
#NOTE if you make the save_to_dir the same as source_dir the original files will be over written
save_to_dir=r'C:\Temp\butterflies\storage'
height=100
width = 100
save_images(source_dir, save_to_dir, height,width)    
view_images(save_to_dir)