zoukankan      html  css  js  c++  java
  • GDAL读写矢量文件——Python

    在Python中使用OGR时,先要导入OGR库,如果需要对中文的支持,还需要导入GDAL库,具体代码如下。Python创建的shp结果如图1所示。

    图1 Python创建矢量结果

    1 #-*- coding: cp936 -*-
    2 try:
    3          from osgeo import gdal
    4          from osgeo import ogr
    5 exceptImportError:
    6          import gdal
    7          import ogr

    1.读取矢量

     1 #-*- coding: cp936 -*-
     2 try:
     3          from osgeo import gdal
     4          from osgeo import ogr
     5 exceptImportError:
     6          import gdal
     7          import ogr
     8  
     9 defReadVectorFile():
    10          # 为了支持中文路径,请添加下面这句代码
    11          gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
    12          # 为了使属性表字段支持中文,请添加下面这句
    13          gdal.SetConfigOption("SHAPE_ENCODING","")
    14  
    15          strVectorFile ="E:\Datum\GDALCsTest\Debug\beijing.shp"
    16  
    17          # 注册所有的驱动
    18          ogr.RegisterAll()
    19  
    20          #打开数据
    21          ds = ogr.Open(strVectorFile, 0)
    22          if ds == None:
    23                    print("打开文件【%s】失败!", strVectorFile)
    24                    return
    25  
    26          print("打开文件【%s】成功!", strVectorFile)
    27  
    28          # 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个
    29          iLayerCount = ds.GetLayerCount()
    30  
    31          # 获取第一个图层
    32          oLayer = ds.GetLayerByIndex(0)
    33          if oLayer == None:
    34                    print("获取第%d个图层失败!
    ", 0)
    35                    return
    36  
    37          # 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
    38          oLayer.ResetReading()
    39  
    40          # 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容
    41          oLayer.SetAttributeFilter(""NAME99"LIKE "北京市市辖区"")
    42  
    43          # 通过指定的几何对象对图层中的要素进行筛选
    44          #oLayer.SetSpatialFilter()
    45  
    46          # 通过指定的四至范围对图层中的要素进行筛选
    47          #oLayer.SetSpatialFilterRect()
    48  
    49          # 获取图层中的属性表表头并输出
    50          print("属性表结构信息:")
    51          oDefn = oLayer.GetLayerDefn()
    52          iFieldCount = oDefn.GetFieldCount()
    53          for iAttr in range(iFieldCount):
    54                    oField =oDefn.GetFieldDefn(iAttr)
    55                    print( "%s: %s(%d.%d)" % ( 
    56                                      oField.GetNameRef(),
    57                                      oField.GetFieldTypeName(oField.GetType() ), 
    58                                      oField.GetWidth(),
    59                                      oField.GetPrecision()))
    60  
    61          # 输出图层中的要素个数
    62          print("要素个数 = %d", oLayer.GetFeatureCount(0))
    63  
    64          oFeature = oLayer.GetNextFeature()
    65          # 下面开始遍历图层中的要素
    66          while oFeature is not None:
    67                    print("当前处理第%d个: 
    属性值:", oFeature.GetFID())
    68                    # 获取要素中的属性表内容
    69                    for iField inrange(iFieldCount):
    70                             oFieldDefn =oDefn.GetFieldDefn(iField)
    71                             line =  " %s (%s) = " % ( 
    72                                                oFieldDefn.GetNameRef(),
    73                                                ogr.GetFieldTypeName(oFieldDefn.GetType()))
    74  
    75                             ifoFeature.IsFieldSet( iField ):
    76                                      line = line+ "%s" % (oFeature.GetFieldAsString( iField ) )
    77                             else:
    78                                      line = line+ "(null)"
    79  
    80                             print(line)
    81         
    82                    # 获取要素中的几何体
    83                    oGeometry =oFeature.GetGeometryRef()
    84  
    85                    # 为了演示,只输出一个要素信息
    86                    break
    87  
    88          print("数据集关闭!")

    执行上面的代码,如果不设置属性过滤,输出内容如图3‑9上半部分所示,如过设置了属性过滤,输出内容如图3‑9下半部分所示。(Python输出的中文转为编码了)。

    图2 OGR库使用Python读取矢量示例

    2.写入矢量

    在使用Python创建矢量图形的时候,使用的WKT格式的字符串来进行创建。也可以使用其他的方式进行创建。代码如下,写出来的矢量图形和属性表如图1所示。

     1 #-*- coding: cp936 -*-
     2 try:
     3          from osgeo import gdal
     4          from osgeo import ogr
     5 exceptImportError:
     6          import gdal
     7          import ogr
     8  
     9 defWriteVectorFile():
    10          # 为了支持中文路径,请添加下面这句代码
    11          gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
    12          # 为了使属性表字段支持中文,请添加下面这句
    13          gdal.SetConfigOption("SHAPE_ENCODING","")
    14  
    15          strVectorFile ="E:\TestPolygon.shp"
    16  
    17          # 注册所有的驱动
    18          ogr.RegisterAll()
    19  
    20          # 创建数据,这里以创建ESRI的shp文件为例
    21          strDriverName = "ESRIShapefile"
    22          oDriver =ogr.GetDriverByName(strDriverName)
    23          if oDriver == None:
    24                    print("%s 驱动不可用!
    ", strDriverName)
    25                    return
    26         
    27          # 创建数据源
    28          oDS =oDriver.CreateDataSource(strVectorFile)
    29          if oDS == None:
    30                    print("创建文件【%s】失败!", strVectorFile)
    31                    return
    32  
    33          # 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定
    34          papszLCO = []
    35          oLayer =oDS.CreateLayer("TestPolygon", None, ogr.wkbPolygon, papszLCO)
    36          if oLayer == None:
    37                    print("图层创建失败!
    ")
    38                    return
    39  
    40          # 下面创建属性表
    41          # 先创建一个叫FieldID的整型属性
    42          oFieldID =ogr.FieldDefn("FieldID", ogr.OFTInteger)
    43          oLayer.CreateField(oFieldID, 1)
    44  
    45          # 再创建一个叫FeatureName的字符型属性,字符长度为50
    46          oFieldName =ogr.FieldDefn("FieldName", ogr.OFTString)
    47          oFieldName.SetWidth(100)
    48          oLayer.CreateField(oFieldName, 1)
    49  
    50          oDefn = oLayer.GetLayerDefn()
    51  
    52          # 创建三角形要素
    53          oFeatureTriangle = ogr.Feature(oDefn)
    54          oFeatureTriangle.SetField(0, 0)
    55          oFeatureTriangle.SetField(1, "三角形")
    56          geomTriangle =ogr.CreateGeometryFromWkt("POLYGON ((0 0,20 0,10 15,0 0))")
    57          oFeatureTriangle.SetGeometry(geomTriangle)
    58          oLayer.CreateFeature(oFeatureTriangle)
    59  
    60          # 创建矩形要素
    61          oFeatureRectangle = ogr.Feature(oDefn)
    62          oFeatureRectangle.SetField(0, 1)
    63          oFeatureRectangle.SetField(1, "矩形")
    64          geomRectangle =ogr.CreateGeometryFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))")
    65          oFeatureRectangle.SetGeometry(geomRectangle)
    66          oLayer.CreateFeature(oFeatureRectangle)
    67  
    68          # 创建五角形要素
    69          oFeaturePentagon = ogr.Feature(oDefn)
    70          oFeaturePentagon.SetField(0, 2)
    71          oFeaturePentagon.SetField(1, "五角形")
    72          geomPentagon =ogr.CreateGeometryFromWkt("POLYGON ((70 0,85 0,90 15,80 30,65 15,700))")
    73          oFeaturePentagon.SetGeometry(geomPentagon)
    74          oLayer.CreateFeature(oFeaturePentagon)
    75  
    76          oDS.Destroy()
    77          print("数据集创建完成!
    ")

    3.矢量数据管理

     1 defVectorDelete(strVectorFile):
     2          # 注册所有的驱动
     3          ogr.RegisterAll()
     4  
     5          oDriver = None
     6          #打开矢量
     7          oDS = ogr.Open(strVectorFile, 0)
     8          if oDS == None:
     9                    os.remove(strVectorFile)
    10                    return
    11  
    12          oDriver = oDS.GetDriver()
    13          if oDriver == None:
    14                    os.remove(strVectorFile)
    15                    return
    16  
    17          ifoDriver.DeleteDataSource(strVectorFile) == ogr.OGRERR_NONE:
    18                    return
    19          else:
    20                    os.remove(strVectorFile)
    21  
    22 defVectorRename(strOldFile, strNewFile):
    23          # 注册所有的驱动
    24          ogr.RegisterAll()
    25  
    26          oDriver = None
    27          #打开矢量
    28          oDS = Ogr.Open(strOldFile, 0)
    29          if oDS == None :
    30                    os.rename(strOldFile,strNewFile)
    31                    return
    32  
    33          oDriver = oDS.GetDriver()
    34          if oDriver == None:
    35                    os.rename(strOldFile,strNewFile)
    36                    return
    37  
    38          oDDS = oDriver.CopyDataSource(oDS,strNewFile, None)
    39          if oDDS == None:
    40                    os.rename(strOldFile,strNewFile)
    41  
    42          if oDriver.DeleteDataSource(strOldFile)== ogr.OGRERR_NONE:
    43                    return
    44          else :
    45                    os.rename(strOldFile,strNewFile)

    文章来源:http://blog.csdn.net/liminlu0314/article/details/8828983

  • 相关阅读:
    前端学习(1)~html标签讲解(一)
    前端学习(0)~vscode工具使用
    微服务之部署
    分解单块系统
    c#之线程基础(一)
    如何在windows 7 上使用docker
    CodeForces 995B Suit and Tie(贪心,暴力)
    CodeForces 993B Open Communication(STL 模拟)
    CodeForces 993A Two Squares(数学 几何)
    CodeForces 996B World Cup(思维)
  • 原文地址:https://www.cnblogs.com/qiernonstop/p/4005785.html
Copyright © 2011-2022 走看看