import os import numpy as np from PIL import Image import tensorflow as tf from…
- User
import os import numpy as np from PIL import Image import tensorflow as tf from keras.models import Sequential from keras.layers import LSTM, Dense, Reshape import matplotlib.pyplot as plt
圖片尺寸
IMG_HEIGHT = 128 IMG_WIDTH = 128 NUM_PIXELS = IMG_HEIGHT * IMG_WIDTH
設置圖像和 mask 的路徑
image_dir = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\north\Finish\train_patches\train" mask_dir = r"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\data\north\Finish\train_patches_mask\train"
遍歷文件夾,讀取圖像和對應的 mask
images = [] masks = []
for img_file in sorted(os.listdir(image_dir)): if img_file.endswith(".jpg"): # 加載圖像 img_path = os.path.join(image_dir, img_file) img = Image.open(img_path).convert("L") # 轉為灰度圖像 img = img.resize((IMG_HEIGHT, IMG_WIDTH)) # 確保大小一致 img = np.array(img).astype(np.float32) / 255.0 # 標準化到 [0, 1] images.append(img)
# 加載對應的 mask mask_file = img_file # 假設 mask 和 img 文件名相同 mask_path = os.path.join(mask_dir, mask_file) mask = Image.open(mask_path).convert("L") mask = mask.resize((IMG_HEIGHT, IMG_WIDTH)) # 確保大小一致 mask = np.array(mask).astype(np.float32) / 255.0 # 標準化到 [0, 1] masks.append(mask)將圖像和 mask 轉換為 numpy 數組
images = np.array(images) masks = np.array(masks)
將圖像和 mask 展開為一維
images_flat = images.reshape(len(images), NUM_PIXELS) # 將每張圖片展開為一維 masks_flat = masks.reshape(len(masks), NUM_PIXELS, 1) # 將每張mask展開為一維
創建 LSTM 模型
model = Sequential() model.add(Reshape((NUM_PIXELS, 1), input_shape=(NUM_PIXELS,))) # 調整輸入形狀 model.add(LSTM(128, return_sequences=True)) model.add(LSTM(64, return_sequences=True)) model.add(Dense(1, activation='sigmoid')) # 用於二值分類
編譯模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
訓練模型
model.fit(images_flat, masks_flat, epochs=10, batch_size=1)
進行預測(以第一張圖像為例)
predicted_mask_flat = model.predict(images_flat[0].reshape(1, NUM_PIXELS))
將預測結果轉回 128x128 的形狀,進行二值化
predicted_mask = (predicted_mask_flat > 0.5).astype(np.uint8).reshape((IMG_HEIGHT, IMG_WIDTH))
使用 matplotlib 顯示預測的二值化圖像
plt.imshow(predicted_mask, cmap='gray') # 顯示為灰度圖 plt.title('Predicted Binary Mask') plt.show()
#####要求保存模型至"C:\Users\jack8\OneDrive\LSTM and ARIMA\LSTM\Model"
- Assistant