Python+OGR库学习(六):批量投影转换(调用自定义函数和模块)

时间:2024-03-26 22:15:34

关键思路

1、批量转换:定义投影转换函数,参数设置输入输出文件名,输入输出坐标系
2、内部功能:针对每一个输入文件,字段属性批量定义(操作对象是layer)、字段值批量写入(操作对象是feature)

代码思路

1、定义.py文件,含3个函数:
字段属性批量定义
字段值批量写入
投影转换:其中需要调用上面2个函数
3、导入以上自定义模块,遍历文件夹,批量投影转换

代码——投影转换模块

#! usr/bin/env python3
# -*- coding:utf-8 -*-

#定义函数:批量复制字段属性
import ogr,osr,os
def CopyFields(inlayer,outlayer):
    featuredefn = inlayer.GetLayerDefn()
    fieldcount = featuredefn.GetFieldCount()
    for field in range(fieldcount):
        outlayer.CreateField(featuredefn.GetFieldDefn(field))
#定义函数,批量复制字段值
def CopyValue(infeature,outfeature):
    cnfield = infeature.GetFieldCount()
    for i in range(cnfield):
        fieldname = infeature.GetFieldDefnRef(i).GetName()
        outfeature.SetField(fieldname,infeature.GetField(fieldname))
#定义投影转换函数
def reproject(infn,outfn,inEPSG,outEPSG):
    #投影参数设置
    inosr = osr.SpatialReference()
    inosr.ImportFromEPSG(inEPSG)

    outosr = osr.SpatialReference()
    outosr.ImportFromEPSG(outEPSG)

    trans = osr.CoordinateTransformation(inosr,outosr)

    #读取输入文件
    driver = ogr.GetDriverByName('ESRI Shapefile')
    inds = ogr.Open(infn,0)
    inLayer = inds.GetLayer()
    #创建输出文件
    if os.path.exists(outfn):
        driver.DeleteDataSource(outfn)
    outds = driver.CreateDataSource(outfn)
    outLayer = outds.CreateLayer(os.path.basename(outfn)[:-4],geom_type = inLayer.GetLayerDefn().GetGeomType())
    #复制属性表定义
    CopyFields(inLayer,outLayer)
    #读取输出属性表信息
    outfeaturedefn = outLayer.GetLayerDefn()
    #遍历输入要素,复制到新文件
    infeature = inLayer.GetNextFeature()
    while infeature:
        #投影转换对象geometry
        geom = infeature.GetGeometryRef()
        geom.Transform(trans)
        #创建输出要素
        outfeature = ogr.Feature(outfeaturedefn)
        #复制字段值
        CopyValue(infeature,outfeature)
        #添加几何体
        outfeature.SetGeometry(geom)
        #添加要素到图层
        outLayer.CreateFeature(outfeature)
        #清除缓存,获取下一输入要素
        infeature.Destroy()
        outfeature.Destroy()
        infeature = inLayer.GetNextFeature()
    #清除dataasource
    inds.Destroy()
    outds.Destroy()
    #写入投影文件
    outosr.MorphFromESRI()
    prjfile = open(outfn.replace('.shp','.prj'),'w')
    prjfile.write(outosr.ExportToWkt())
    prjfile.close()

代码——调用

from Mymoudle import reprojection
import os,glob
os.chdir(r'F:\Python+gdal\7weeks数据\7weeks数据\ospy_data3\ospy3_data')
filelist = glob.glob('*.shp')
for infn in filelist:
    outfn = infn.replace('.shp','_repro.shp')
    reprojection.reproject(infn,outfn,26912,4269)
    #print(file)

结果

Python+OGR库学习(六):批量投影转换(调用自定义函数和模块)

待转换文件列表

Python+OGR库学习(六):批量投影转换(调用自定义函数和模块)

转换后文件列表

Python+OGR库学习(六):批量投影转换(调用自定义函数和模块)

待转换文件坐标系

Python+OGR库学习(六):批量投影转换(调用自定义函数和模块)

转换后坐标系
**还有一些ogr库常用函数,需要练习**