CNN变化检测代码下载
时间: 2023-06-11 20:06:09 浏览: 101
变化检测新下代码.rar
以下是一个基于TensorFlow的CNN变化检测代码示例,可以用于检测遥感图像中的变化:
```
import tensorflow as tf
import numpy as np
import os
import argparse
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument("--train_data_dir", default="./train_data", help="Directory containing the train data.")
parser.add_argument("--test_data_dir", default="./test_data", help="Directory containing the test data.")
parser.add_argument("--epochs", default=10, type=int, help="Number of training epochs.")
parser.add_argument("--batch_size", default=32, type=int, help="Batch size.")
parser.add_argument("--lr", default=0.001, type=float, help="Learning rate.")
parser.add_argument("--model_dir", default="./model", help="Directory to save the trained model.")
args = parser.parse_args()
def load_data(data_dir):
image_dir = os.path.join(data_dir, "images")
label_dir = os.path.join(data_dir, "labels")
image_files = os.listdir(image_dir)
label_files = os.listdir(label_dir)
image_files.sort()
label_files.sort()
images = []
labels = []
for i in range(len(image_files)):
image_path = os.path.join(image_dir, image_files[i])
label_path = os.path.join(label_dir, label_files[i])
image = np.array(Image.open(image_path).convert("RGB"))
label = np.array(Image.open(label_path).convert("L")) // 255
images.append(image)
labels.append(label)
images = np.array(images)
labels = np.array(labels)
return images, labels
def create_model():
inputs = tf.keras.layers.Input(shape=(256, 256, 3))
x = tf.keras.layers.Conv2D(32, 3, activation="relu")(inputs)
x = tf.keras.layers.MaxPooling2D()(x)
x = tf.keras.layers.Conv2D(64, 3, activation="relu")(x)
x = tf.keras.layers.MaxPooling2D()(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(128, activation="relu")(x)
outputs = tf.keras.layers.Dense(1, activation="sigmoid")(x)
model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
return model
def train():
train_images, train_labels = load_data(args.train_data_dir)
test_images, test_labels = load_data(args.test_data_dir)
model = create_model()
model.compile(optimizer=tf.keras.optimizers.Adam(lr=args.lr),
loss="binary_crossentropy",
metrics=["accuracy"])
model.fit(train_images, train_labels,
epochs=args.epochs,
batch_size=args.batch_size,
validation_data=(test_images, test_labels))
model.save(args.model_dir)
def predict(image_path, model_path):
model = tf.keras.models.load_model(model_path)
image = np.array(Image.open(image_path).convert("RGB"))
image = np.expand_dims(image, axis=0)
prediction = model.predict(image)
return prediction[0][0]
if __name__ == "__main__":
train()
```
使用方法:
1. 将训练数据放在`--train_data_dir`指定的目录下,其中包含两个子目录:`images`和`labels`,分别存放原始图像和变化检测标签。
2. 将测试数据放在`--test_data_dir`指定的目录下,格式同训练数据。
3. 运行`python cnn_change_detection.py`进行训练,训练完成后模型会被保存在`--model_dir`指定的目录下。
4. 使用`predict`函数可以对单张图像进行预测,其中`image_path`为待预测图像的路径,`model_path`为训练好的模型路径。返回值为预测的变化概率值(0到1之间)。
阅读全文