• 【Python&GIS】基于Python批量合并矢量数据


            老样子最近有项目需要将N个矢量文件合并成一个,总不能用ArcGIS一个个导入吧。所以我就想着用Python编个程序实现批量合并矢量。我之前也发了一些关于Python操作矢量数据的文章:【Python&GIS】Python处理矢量数据的基本操作(查询、修改、删除、新建),如果大家感兴趣可以去我的主页看看,给我点个关注!

    一、导入库

    1. import os
    2. from osgeo import ogr

    二、合并shp

            整体的思路就是创建一个空的shp资源,然后遍历文件夹中所有的shp,然后针对每一个shp再遍历它的要素,将每个要素写入创建的新shp中。需要注意的是最后需要释放内存,不然数据不会写入shp。

    1. def Merge_shp(path):
    2. print("-----------------合并shp-----------------")
    3. path_lists = os.listdir(path)
    4. src_proj = None
    5. for c in path_lists:
    6. if c.endswith(".shp"):
    7. print(c)
    8. ds = ogr.Open(path+c)
    9. layer = ds.GetLayer()
    10. # 打开需要转换的矢量数据,获取图层
    11. src_proj = layer.GetSpatialRef()
    12. break
    13. # 获取其源坐标信息
    14. output_file = path+"Merge.shp"
    15. driver = ogr.GetDriverByName('ESRI Shapefile')
    16. output_ds = driver.CreateDataSource(output_file)
    17. output_layer = output_ds.CreateLayer("Shp", srs=src_proj, geom_type=ogr.wkbMultiPolygon)
    18. new_field = ogr.FieldDefn('value', ogr.OFTReal) # 给目标shp文件添加一个字段,用来存储原始栅格的pixel value
    19. output_layer.CreateField(new_field)
    20. for i in range(0, len(path_lists)):
    21. if path_lists[i].endswith(".shp"):
    22. print("正在合并%s......" % path_lists[i])
    23. input_ds = ogr.Open(path + path_lists[i])
    24. input_layer = input_ds.GetLayer()
    25. for feature in input_layer:
    26. output_layer.CreateFeature(feature.Clone())
    27. input_ds = None
    28. output_ds = None

    三、获取要素面积

            我这里给shp添加了一个新的字段,用来计算面积。大家视情况而定,这个可以没有。

    1. def Get_polygon_area(path_shp):
    2. """
    3. :param path_shp: 输入矢量文件
    4. :return:
    5. """
    6. print("---------------获取矢量面积---------------")
    7. driver = ogr.GetDriverByName("ESRI Shapefile") # 创建数据驱动
    8. ds = driver.Open(path_shp, 1) # 创建数据资源
    9. layer = ds.GetLayer()
    10. new_field = ogr.FieldDefn("Area", ogr.OFTReal) # 创建新的字段
    11. # new_field.SetWidth(32)
    12. # new_field.SetPrecision(16)
    13. layer.CreateField(new_field)
    14. for feature in layer:
    15. geom = feature.GetGeometryRef()
    16. geom2 = geom.Clone()
    17. area = geom2.GetArea() # 默认为平方米
    18. # area = area / 1000000 # 转化为平方公里
    19. feature.SetField("Area", area)
    20. # feature.GetField('Area')
    21. layer.SetFeature(feature)
    22. ds = None

    四、完整代码

    1. # -*- coding: utf-8 -*-
    2. """
    3. @Time : 2023/10/20 11:56
    4. @Auth : RS迷途小书童
    5. @File :Vector Data Batch Merge.py
    6. @IDE :PyCharm
    7. @Purpose:矢量数据批量合并成一个文件并计算面积
    8. """
    9. import os
    10. from osgeo import ogr
    11. def Merge_shp(path):
    12. print("-----------------合并shp-----------------")
    13. path_lists = os.listdir(path)
    14. src_proj = None
    15. for c in path_lists:
    16. if c.endswith(".shp"):
    17. print(c)
    18. ds = ogr.Open(path+c)
    19. layer = ds.GetLayer()
    20. # 打开需要转换的矢量数据,获取图层
    21. src_proj = layer.GetSpatialRef()
    22. break
    23. # 获取其源坐标信息
    24. output_file = path+"Merge.shp"
    25. driver = ogr.GetDriverByName('ESRI Shapefile')
    26. output_ds = driver.CreateDataSource(output_file)
    27. output_layer = output_ds.CreateLayer("Shp", srs=src_proj, geom_type=ogr.wkbMultiPolygon)
    28. new_field = ogr.FieldDefn('value', ogr.OFTReal) # 给目标shp文件添加一个字段,用来存储原始栅格的pixel value
    29. output_layer.CreateField(new_field)
    30. for i in range(0, len(path_lists)):
    31. if path_lists[i].endswith(".shp"):
    32. print("正在合并%s......" % path_lists[i])
    33. input_ds = ogr.Open(path + path_lists[i])
    34. input_layer = input_ds.GetLayer()
    35. for feature in input_layer:
    36. output_layer.CreateFeature(feature.Clone())
    37. input_ds = None
    38. output_ds = None
    39. def Get_polygon_area(path_shp):
    40. """
    41. :param path_shp: 输入矢量文件
    42. :return:
    43. """
    44. print("---------------获取矢量面积---------------")
    45. driver = ogr.GetDriverByName("ESRI Shapefile") # 创建数据驱动
    46. ds = driver.Open(path_shp, 1) # 创建数据资源
    47. layer = ds.GetLayer()
    48. new_field = ogr.FieldDefn("Area", ogr.OFTReal) # 创建新的字段
    49. # new_field.SetWidth(32)
    50. # new_field.SetPrecision(16)
    51. layer.CreateField(new_field)
    52. for feature in layer:
    53. geom = feature.GetGeometryRef()
    54. geom2 = geom.Clone()
    55. area = geom2.GetArea() # 默认为平方米
    56. # area = area / 1000000 # 转化为平方公里
    57. feature.SetField("Area", area)
    58. # feature.GetField('Area')
    59. layer.SetFeature(feature)
    60. ds = None
    61. if __name__ == "__main__":
    62. path1 = r"G:/2/"
    63. Merge_shp(path1)
    64. Get_polygon_area(path1+"Merge.shp")

            大家在使用时只需要将你要合并的shp全部放入一个文件夹,然后再将main中文件夹路径改成自己的就行了,程序最后会在该目录下生成Merge.shp文件,这个就是合并之后的结果。

  • 相关阅读:
    激光共聚焦如何选择荧光染料
    go语言|数据结构:单链表(2)
    Go语言连不上 Mysql
    2023山东建筑大学考研介绍
    基于Prometheus快速搭建网络质量监控平台
    详细讲解库函数的使用及模拟实现(提升对库函数的理解和运用)
    SSTI服务端模板注入漏洞原理详解及利用姿势集锦
    bootstrap按钮
    js的同步异步
    【面试经典150 | 】颠倒二进制位
  • 原文地址:https://blog.csdn.net/m0_56729804/article/details/133946884