【GDAL应用】面要素转线要素

1 实现功能

把面状shp矢量数据(面要素属性字段FID_1 = 1)转化为线状shp矢量数据。

2 实现代码

import os
from osgeo import ogr
import argparse
import shutil
import time
import traceback
import sys

# 用于打包所需要的依赖库,加入环境变量
# proj_str = os.path.dirname(sys.argv[0]) + '/proj'
# os.environ['PROJ_LIB'] = proj_str


def poly2line(polyfn, linefn):
    """
        This function is used to make polygon convert to line
    :param polyfn: the path of input, the shapefile of polygon
    :param linefn: the path of output, the shapefile of line
    :return:
    """
    driver = ogr.GetDriverByName('ESRI Shapefile')
    polyds = ogr.Open(polyfn, 0)
    polyLayer = polyds.GetLayer()
    spatialref = polyLayer.GetSpatialRef()
    # 创建输出文件
    if os.path.exists(linefn):
        driver.DeleteDataSource(linefn)
    lineds = driver.CreateDataSource(linefn)
    linelayer = lineds.CreateLayer(linefn, srs=spatialref, geom_type=ogr.wkbLineString)
    featuredefn = linelayer.GetLayerDefn()
    # 获取ring到几何体
    # geomline = ogr.Geometry(ogr.wkbGeometryCollection)
    polyLayer.SetAttributeFilter("FID_1 = 1")

    oNewField = ogr.FieldDefn("FID_1", ogr.OFTInteger)
    # 设置精度
    # oNewField.SetPrecision(10)
    linelayer.CreateField(oNewField)

    for feat in polyLayer:
        geom = feat.GetGeometryRef()
        ring = geom.GetGeometryRef(0)
        # geomcoll.AddGeometry(ring)
        outfeature = ogr.Feature(featuredefn)  # 实例化
        outfeature.SetField("FID_1", 1)
        outfeature.SetGeometry(ring)

        linelayer.CreateFeature(outfeature)
        outfeature = None

##  将FID_1=0的要素也转为线要素
##    polyLayer.SetAttributeFilter("FID_1 = 0")
##    for feat in polyLayer:
##        geom = feat.GetGeometryRef()
##        ring = geom.GetGeometryRef(0)
##        # geomcoll.AddGeometry(ring)
##        outfeature = ogr.Feature(featuredefn)  # 实例化
##        outfeature.SetField("FID_1", 0)
##        outfeature.SetGeometry(ring)
##
##        linelayer.CreateFeature(outfeature)
##        outfeature = None


if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--poly', type=str, default='./poly', help=u'面样本路径')
    parser.add_argument('-l', '--line', type=str, default='./line', help=u'线样本路径')
    args = parser.parse_args()
    polyfn = args.poly
    linefn = args.line

    polyfn = r"F:\sample1\sample\sample"
##    linefn = r"F:\sample1\sample\new_sample"

    t1 = time.time()

    path_list = []
    temp_list = []
    fileFolders = os.listdir(polyfn)
    try:
        for fileFolder in fileFolders:
            real_path = os.path.join(polyfn, fileFolder)
            if os.path.isdir(real_path):
                # print(real_path)
                files = os.listdir(real_path)
                for file in files:
                    if file[-3:] == "tif":
                        # temp_list.append(os.path.join(real_path, file))
                        refer_Name = file.split(".")[0] + "_V1"
                        dirpath = os.path.join(linefn, refer_Name)
                        if not os.path.exists(dirpath):
                            os.mkdir(dirpath)
                        for file in files:
                            if (file.split(".")[0] + ".t") in file:
                                shutil.copy(os.path.join(real_path, file), dirpath)
                    if file[-3:] == "shp":
                        temp_list.append(os.path.join(real_path, file))
                        # refer_Name = file[0:-12] + "_V1"
                        dirpath = os.path.join(linefn, refer_Name)

                path_list.append(temp_list)
                temp_list = []

        for i in path_list:
            shpName = os.path.split(i[0])[1]  # 返回文件路径和文件名
            lineName = shpName[0:-9] + "_LINE.shp"
            print(lineName)
            dirpath = os.path.join(linefn, shpName[0:-12] + "_V1")

            if not os.path.exists(dirpath):
                os.mkdir(dirpath)
            out_shpName = os.path.join(dirpath, lineName)
            poly2line(i[0], out_shpName)
        t2 = time.time()
        print("%ss" % (t2 - t1))
    except:
        traceback.print_exc()

3 实现效果

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值