1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
| import numpy as np import rasterio import rasterio.plot from rasterio.mask import mask from rasterio.warp import reproject, calculate_default_transform, Resampling as WarpResampling import geopandas as gpd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from shapely.geometry import box import pandas as pd import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] matplotlib.rcParams['axes.unicode_minus'] = False
def read_base_tif(file_path): with rasterio.open(file_path) as src: data = src.read(1) profile = src.profile.copy() transform = src.transform crs = src.crs bounds = src.bounds return data, profile, transform, crs, bounds
def read_intensity_tif(file_path): with rasterio.open(file_path) as src: data = src.read(1) profile = src.profile.copy() transform = src.transform crs = src.crs bounds = src.bounds return data, profile, transform, crs, bounds
def read_geojson_files(file_list): gdf_list = [] for file in file_list: gdf = gpd.read_file(file) gdf_list.append(gdf) combined_gdf = pd.concat(gdf_list, ignore_index=True) combined_gdf = gpd.GeoDataFrame(combined_gdf) return combined_gdf
def extract_overlapping_region(base_data, base_transform, base_crs, base_bounds, intensity_data, intensity_transform, intensity_crs, intensity_bounds): if base_crs != intensity_crs: raise ValueError("base.tif 和 intensity.tif 的坐标参考系不一致,请进行坐标转换。")
base_geom = box(*base_bounds) intensity_geom = box(*intensity_bounds) overlap_geom = base_geom.intersection(intensity_geom)
if overlap_geom.is_empty: raise ValueError("base.tif 和 intensity.tif 没有重叠区域。")
overlap_geojson = [overlap_geom.__geo_interface__]
with rasterio.open('base.tif') as src: base_overlap_data, base_overlap_transform = mask(src, overlap_geojson, crop=True) base_overlap_meta = src.meta.copy() base_overlap_meta.update({ "height": base_overlap_data.shape[1], "width": base_overlap_data.shape[2], "transform": base_overlap_transform })
with rasterio.open('intensity.tif') as src: intensity_overlap_data, intensity_overlap_transform = mask(src, overlap_geojson, crop=True) intensity_overlap_meta = src.meta.copy() intensity_overlap_meta.update({ "height": intensity_overlap_data.shape[1], "width": intensity_overlap_data.shape[2], "transform": intensity_overlap_transform })
base_overlap_resampled = np.empty_like(intensity_overlap_data, dtype=base_overlap_data.dtype)
reproject( source=base_overlap_data, destination=base_overlap_resampled, src_transform=base_overlap_transform, src_crs=base_crs, dst_transform=intensity_overlap_transform, dst_crs=intensity_crs, resampling=WarpResampling.nearest )
return base_overlap_resampled[0], intensity_overlap_data[0], intensity_overlap_transform, intensity_crs
def calculate_risk_probability(intensity, base): A = 0.00250165038535077 * np.exp(0.6931 * intensity)
exponent = - (A + base)
with np.errstate(over='ignore', invalid='ignore'): result = 1 / (1 + np.exp(exponent))
result = np.nan_to_num(result, nan=0.0, posinf=0.0, neginf=0.0) return result
def classify_risk_levels(probability): risk_levels = np.zeros_like(probability, dtype=np.uint8)
risk_levels[probability >= 0.1] = 5 risk_levels[(probability >= 0.01) & (probability < 0.1)] = 4 risk_levels[(probability >= 0.001) & (probability < 0.01)] = 3 risk_levels[(probability >= 0.0001) & (probability < 0.001)] = 2 risk_levels[probability < 0.0001] = 1
return risk_levels
def visualize_risk(risk_levels, transform, crs, combined_gdf): colors = ['white', 'blue', 'yellow', 'orange', 'red'] cmap = ListedColormap(colors)
fig, ax = plt.subplots(figsize=(10, 8))
rasterio.plot.show(risk_levels, transform=transform, cmap=cmap, ax=ax) ax.set_title("次生地质灾害风险概率图") ax.set_xlabel('经度') ax.set_ylabel('纬度')
labels = ['低风险', '中低风险', '中风险', '中高风险', '高风险'] patches = [plt.plot([], [], marker="s", ms=10, ls="", mec=None, color=colors[i], label="{:s}".format(labels[i]))[0] for i in range(len(colors))] ax.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc='upper left')
if combined_gdf.crs != crs: combined_gdf = combined_gdf.to_crs(crs)
width = risk_levels.shape[1] height = risk_levels.shape[0] left, top = transform * (0, 0) right, bottom = transform * (width, height) overlap_geom = box(left, bottom, right, top) overlap_gdf = gpd.GeoDataFrame(geometry=[overlap_geom], crs=crs) clipped_gdf = gpd.overlay(combined_gdf, overlap_gdf, how='intersection')
clipped_gdf.boundary.plot(ax=ax, edgecolor='black', linewidth=0.5)
for idx, row in clipped_gdf.iterrows(): centroid = row['geometry'].centroid ax.text(centroid.x, centroid.y, row.get('name', '未知'), fontsize=6, ha='center', va='center', color='black')
plt.show()
plt.savefig('final_result.tif', dpi=300, bbox_inches='tight', format='tif') print("风险概率图已成功保存为 'final_result.tif'。")
if __name__ == "__main__": base_data, base_profile, base_transform, base_crs, base_bounds = read_base_tif('base.tif')
intensity_data, intensity_profile, intensity_transform, intensity_crs, intensity_bounds = read_intensity_tif('intensity.tif')
sichuan_json_files = ['阿坝藏族羌族自治州.json', '成都市.json', '德阳市.json', '甘孜藏族自治州.json', '乐山市.json', '凉山彝族自治州.json', '眉山市.json', '绵阳市.json', '内江市.json', '遂宁市.json', '雅安市.json', '宜宾市.json', '资阳市.json', '自贡市.json'] xizang_json_files = ['昌都市.json', '那曲市.json', '日喀则市.json', '山南市.json', '林芝市.json'] all_json_files = sichuan_json_files + xizang_json_files
combined_gdf = read_geojson_files(all_json_files)
base_overlap_data, intensity_overlap_data, overlap_transform, overlap_crs = extract_overlapping_region( base_data, base_transform, base_crs, base_bounds, intensity_data, intensity_transform, intensity_crs, intensity_bounds )
risk_probability = calculate_risk_probability(intensity_overlap_data, base_overlap_data)
risk_levels = classify_risk_levels(risk_probability)
out_meta = base_profile.copy() out_meta.update({ "driver": "GTiff", "height": risk_levels.shape[0], "width": risk_levels.shape[1], "transform": overlap_transform, "crs": overlap_crs, "count": 1, "dtype": 'uint8', "nodata": 0 }) with rasterio.open('risk_level.tif', 'w', **out_meta) as dest: dest.write(risk_levels, 1)
visualize_risk(risk_levels, overlap_transform, overlap_crs, combined_gdf)
|