1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- import rasterio
- from rasterio.features import shapes
- import geopandas as gpd
- import numpy as np
- def tif_to_geojson(input_tif, output_geojson, band=1, mask_value=None):
- # 打开TIFF文件
- with rasterio.open(input_tif) as src:
- # 读取指定波段数据
- image = src.read(band)
-
- # 获取坐标变换信息
- transform = src.transform
-
- # 如果指定了mask_value,创建掩码
- mask = None
- if mask_value is not None:
- mask = image != mask_value
-
- # 将栅格数据转换为多边形
- results = (
- {'properties': {'raster_value': v}, 'geometry': s}
- for i, (s, v) in enumerate(
- shapes(image, mask=mask, transform=transform))
- )
-
- # 创建GeoDataFrame
- geodata = gpd.GeoDataFrame.from_features(list(results))
-
- # 设置坐标系
- geodata.crs = src.crs
-
- # 保存为GeoJSON
- geodata.to_file(output_geojson, driver='GeoJSON')
-
- print(f"成功将 {input_tif} 转换为 {output_geojson}")
-
- input_file = r"D:\17417\Documents\backend\Water\Raster\水田.tif" # 替换为你的TIFF文件路径
- output_file = r"D:\17417\Documents\backend\Water\Raster\水田.geojson" # 输出GeoJSON文件路径
- # 可选:指定要忽略的值(如背景值)
- mask_value = 0 # 通常0表示背景
- tif_to_geojson(input_file, output_file, mask_value=mask_value)
|