如何將預處理的影像(在應用 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'
)
uj5u.com熱心網友回復:
下面的代碼有兩個功能。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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/403781.html
標籤:
