Into_Geo.py 1.4 KB

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