遥感影像变化检测--标注实现

变化检测结果标注

标注结果如下:其中红色表示错检,蓝色表示漏检
色彩标注示例

实现代码如下:

Predict = '图片路径'
Rootdict = '根路径'


###############################################################################
# 基础函数
###############################################################################

def load_img_name_list(dataset_path):
    img_name_list = np.loadtxt(dataset_path, dtype=np.str_)
    if img_name_list.ndim == 2:
        return img_name_list[:, 0]
    return img_name_list


def get_img_path(root_dir, img_name):
    return os.path.join(root_dir, 'label', img_name)


def get_changeimg_path(root_dir, img_name):
    return os.path.join(root_dir, Predict, img_name)


def color_label(img1, img2):
    w, h, _ = img1.shape
    # 需要重新赋值,因为图片只读
    img = np.array(img2)

    fp = np.array([255, 255, 255])
    fn = np.array([1, 1, 1])
    for i in range(0, w):
        for j in range(0, h):
            p1 = img1[i][j]
            p2 = img2[i][j]
            # false positive,根据自己需求修改对应颜色
            if ((p2 - p1) == fp).all():
                img[i][j] = [255, 0, 0]
            # false negative
            if ((p2 - p1) == fn).all():
                img[i][j] = [0, 0, 255]
    return img


def save_image(image_numpy, image_path):
    image_pil = Image.fromarray(np.array(image_numpy, dtype=np.uint8))
    image_pil.save(image_path)

###############################################################################
# 颜色标注变化区域
###############################################################################

def change_pics():
    root_dir = Rootdict
    list_path = os.path.join(root_dir, 'list', 'demo.txt')
    save_path = os.path.join(root_dir, 'color_label', Predict)
    os.makedirs(save_path, exist_ok=True)
    img_name_list = load_img_name_list(list_path)
    size = len(img_name_list)
    for index in range(0, size):
        name = img_name_list[index]
        print('process:' + name)
        A_path = get_img_path(root_dir, img_name_list[index % size])
        B_path = get_changeimg_path(root_dir, img_name_list[index % size])
        a = Image.open(A_path)
        b = Image.open(B_path)

        #  灰度值转rgb
        img = np.asarray(a.convert('RGB'))
        img_B = np.asarray(b.convert('RGB'))

        #  颜色转化
        color_img = color_label(img, img_B)
        filename = os.path.join(save_path, name.replace('.jpg', '.png'))
        
        # 图片保存
        save_image(color_img, filename)

if __name__ == '__main__':
    change_pics()
### 遥感影像中道路变化检测Python实现 #### K-means算法用于遥感影像中的应用 对于遥感影像变化检测,尤其是针对特定对象如道路的变化检测,可以利用聚类分析来区分不同类型的地物。K-means作为一种无监督学习方法,在处理此类问题上具有一定的优势[^1]。 ```python from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt from osgeo import gdal def load_image(file_path): dataset = gdal.Open(file_path) image_array = dataset.ReadAsArray() return image_array.transpose((1, 2, 0)) # 加载两个时期的遥感影像数据 image_t1 = load_image('path_to_first_period_road_image') image_t2 = load_image('path_to_second_period_road_image') # 将图像转换成二维数组以便于kmeans计算 reshaped_img_t1 = image_t1.reshape((-1, image_t1.shape[-1])) reshaped_img_t2 = image_t2.reshape((-1, image_t2.shape[-1])) # 使用K-means进行分类 n_clusters = 2 # 假设只有两种类别:路与非路 km_model_t1 = KMeans(n_clusters=n_clusters).fit(reshaped_img_t1) km_model_t2 = KMeans(n_clusters=n_clusters).fit(reshaped_img_t2) # 获取每个像素所属簇标签 labels_t1 = km_model_t1.labels_.reshape(image_t1.shape[:2]) labels_t2 = km_model_t2.labels_.reshape(image_t2.shape[:2]) plt.figure(figsize=(12,6)) plt.subplot(121), plt.imshow(labels_t1), plt.title('First Period Road Segmentation') plt.subplot(122), plt.imshow(labels_t2), plt.title('Second Period Road Segmentation') plt.show() ``` 这段代码展示了如何加载两期遥感影像,并通过K-means算法对其进行分割以识别可能的道路区域。然而,这只是一个初步的结果展示,实际操作还需要进一步细化参数设置以及考虑更多因素的影响。 #### 变化检测的具体流程 为了更精确地捕捉到道路的变化情况,除了上述的基础步骤外,还可以引入其他技术手段辅助判断。例如,可以通过比较前后两次获取的数据之间的差异来进行更加细致化的分析。常用的技术包括但不限于比值法、插值法等[^2]。 ```python difference_map = abs(labels_t1 - labels_t2) fig, ax = plt.subplots() cax = ax.matshow(difference_map, cmap='hot') fig.colorbar(cax) plt.title('Difference Map of Roads Between Two Time Phases') plt.show() changed_pixels = difference_map != 0 percentage_change = (np.sum(changed_pixels) / float(difference_map.size)) * 100 print(f'Percentage change in road area: {percentage_change:.2f}%') ``` 此部分代码构建了一个差分图谱,用来直观显示哪些地方发生了改变;同时也统计出了发生变动的比例数值,有助于评估整体上的变化程度。 #### 结果验证与精度评价 完成以上过程之后,最后一步是对所得结果的质量做出衡量。通常会借助混淆矩阵或其他指标体系来进行定量描述。下面给出了一种简单的准确率评测方式: ```python from sklearn.metrics import confusion_matrix, accuracy_score ground_truth_labels = ... # 这里应该填入真实的标注信息作为参照标准 predicted_changes = changed_pixels.flatten() cm = confusion_matrix(ground_truth_labels, predicted_changes) acc = accuracy_score(ground_truth_labels, predicted_changes) print("Confusion Matrix:\n", cm) print(f"Accuracy Score: {acc*100:.2f} %") ``` 该片段实现了对预测结果同真实状况之间的一致性检验,从而帮助确认所选方案的有效性和可靠性[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值