Exemplo n.º 1
0
def ogr_basic_8():

    ogr.RegisterAll()
    ogr.RegisterAll()
    ogr.RegisterAll()

    return 'success'
Exemplo n.º 2
0
    def readshp(self, input_shp_path):
        if os.path.isfile(input_shp_path):
            filetype = input_shp_path.split(".")[-1]
            gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
            gdal.SetConfigOption("SHAPE_ENCODING", "")
            ogr.RegisterAll()
            self.DriveDict = {
                'shp': ogr.GetDriverByName('ESRI Shapefile'),
                'SHP': ogr.GetDriverByName('ESRI Shapefile'),
                'Geojson': ogr.GetDriverByName('GeoJSON'),
                'geojson': ogr.GetDriverByName('GeoJSON'),
                'pbf': ogr.GetDriverByName('MVT'),
                'mbtiles': ogr.GetDriverByName('MBTiles')
            }
            if filetype in self.DriveDict.keys():
                print("\033[0m# -----Valid vector format :\033[1;32m ",
                      filetype)
                self.Driver = self.DriveDict[filetype]

            self.Input_path = input_shp_path
            self.DataSource = self.Driver.Open(self.Input_path)
            self.meta = self.DataSource.GetMetadata()

            print(
                "\n\033[0m# ----------------------------- Meta Information ----------------------------- #"
            )
            self.print_dict(self.meta)

            print(
                "# ----------------------------- Meta Information ----------------------------- #\n"
            )
            self.Description = self.DataSource.GetDescription()
            print('\033[0m# -----Description :\033[1;32m ', self.Description)
            assert self.DataSource is not None, '\n\n\nERROR-----' + \
                str(input_shp_path) + '  --- Invalid Input Shepefile\n\n\n'
            self.LayerCount = self.DataSource.GetLayerCount()
            print("\033[0m# -----LayerCount\033[1;32m :", self.LayerCount)
            self.LayerDict = {}
            for i in range(self.LayerCount):
                self.Layer = self.DataSource.GetLayer(i)
                print("\033[0m# -----Layer :\033[1;34m ", i,
                      "\033[0m LayerName : \033[1;32m ", self.Layer.GetName(),
                      self.Layer.GetGeometryColumn())
                self.LayerDict[self.Layer.GetName()] = self.Layer

            self.Srs = self.Layer.GetSpatialRef()
            self.Extent = self.Layer.GetExtent()
            print("\033[0m# -----Extent:\033[1;32m ", self.Extent)
            print("\033[0m# -----Alread Load:\033[1;32m ", input_shp_path,
                  "\033[0m")
            print(
                "# -------------------------------- DEFINE DONE ------------------------------- #"
            )

        else:
            print(
                "# ----- \033[5;31m Warning: Vector Class init with wrong path or invalid vector file \nPath:",
                input_shp_path, "\033[0m\n")
Exemplo n.º 3
0
 def OpenData(self, filename):
     ogr.RegisterAll()
     gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
     # 读取字段属性值时设置,否则有中文乱码
     gdal.SetConfigOption("SHAPE_ENCODING", "gbk")
     ds = gdal.OpenEx(filename, gdal.OF_VECTOR)
     if ds is None:
         print("Open failed.%s\n" % filename)
         sys.exit(1)
     return ds
Exemplo n.º 4
0
def save_shp(shp_path: str, geocode_list: List[Dict], geo_info: Dict) -> str:
    if IMPORT_STATE == True:
        # 支持中文路径
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
        # 属性表字段支持中文
        gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")
        # 注册驱动
        ogr.RegisterAll()
        # 创建shp数据
        strDriverName = "ESRI Shapefile"
        oDriver = ogr.GetDriverByName(strDriverName)
        if oDriver == None:
            return "驱动不可用:" + strDriverName
        # 创建数据源
        oDS = oDriver.CreateDataSource(shp_path)
        if oDS == None:
            return "创建文件失败:" + shp_path
        # 创建一个多边形图层
        prosrs = osr.SpatialReference()
        prosrs.ImportFromWkt(geo_info.crs_wkt)
        geosrs = prosrs.CloneGeogCS()
        ct = osr.CoordinateTransformation(prosrs, geosrs)
        geocode_list = __bound2wkt(geocode_list, geo_info.geotf, ct)
        ogr_type = ogr.wkbPolygon
        shpe_name = osp.splitext(osp.split(shp_path)[-1])[0]
        oLayer = oDS.CreateLayer(shpe_name, geosrs, ogr_type)
        if oLayer == None:
            return "图层创建失败!"
        # 创建属性表
        # 创建id字段
        oId = ogr.FieldDefn("id", ogr.OFTInteger)
        oLayer.CreateField(oId, 1)
        # 创建字段
        oAddress = ogr.FieldDefn("clas", ogr.OFTString)
        oLayer.CreateField(oAddress, 1)
        oDefn = oLayer.GetLayerDefn()
        # 创建要素
        # 数据集
        for index, f in enumerate(geocode_list):
            oFeaturePolygon = ogr.Feature(oDefn)
            oFeaturePolygon.SetField("id", index)
            oFeaturePolygon.SetField("clas", f["clas"])
            geomPolygon = ogr.CreateGeometryFromWkt(f["polygon"])
            oFeaturePolygon.SetGeometry(geomPolygon)
            oLayer.CreateFeature(oFeaturePolygon)
        # 创建完成后,关闭进程
        oDS.Destroy()
        return "数据集创建完成!"
    else:
        raise ImportError("can't import gdal, osr, ogr!")
Exemplo n.º 5
0
def combine_all_extent(dic_pr_pscene, p_vector):
    f_vct_ext = p_vector + '/requires/image_extent.shp'
    f_ref = p_vector + '/2000_Merge_ui.shp'

    ref_ref = GS.geo_shape.open(f_ref)
    lyr_ref = ref_ref.get_layer(0)
    proj_in = lyr_ref.spatial_ref
    #---- create new
    ogr.RegisterAll()
    driver = ogr.GetDriverByName("ESRI Shapefile")
    if os.access(f_vct_ext, os.F_OK):
        driver.DeleteDataSource(f_vct_ext)

    ds_out = driver.CreateDataSource(f_vct_ext)
    layer_out = ds_out.CreateLayer("data_extent", srs=proj_in)

    #---- generate new field
    dfn_field = ogr.FieldDefn('PR', ogr.OFTInteger)
    layer_out.CreateField(dfn_field)
    dfn_layer = layer_out.GetLayerDefn()

    #---- batch
    pathrows = dic_pr_pscene.keys()
    pathrows.sort()
    for pathrow in pathrows:
        p_scene = dic_pr_pscene[pathrow]
        f_vct = p_scene + '/data_extent.shp'

        ref_scn = GS.geo_shape.open(f_vct)
        lyr_scn = ref_scn.get_layer(0)
        '''
		count = lyr_scn.layer.GetFeatureCount()
		print pathrow,count
		continue
		'''
        ft = lyr_scn.layer.GetFeature(0)
        geom = ft.GetGeometryRef()
        pr = pathrow[1:4] + pathrow[-3:]

        #print pathrow,geom.IsSimple()
        geom_simp = geom.Simplify(100)

        ft_out = ogr.Feature(dfn_layer)
        ft_out.SetGeometry(geom_simp)
        ft_out.SetField('PR', pr)
        layer_out.CreateFeature(ft_out)
        ft_out.Destroy()
    ds_out.Destroy()
    print f_vct_ext
Exemplo n.º 6
0
def copy2pg_database(ds,
                     ds_layer,
                     layer,
                     layer_name,
                     schema="public",
                     overwrite="YES"):

    # ds, layer = check_ogr_columns(ds_layer, layer)

    options = [
        "OVERWRITE={}".format(overwrite),
        "SCHEMA={}".format(schema),
        "SPATIAL_INDEX=GIST",
        "FID=ogc_fid",
        "PRECISION=NO",
    ]
    try:
        geom_type = layer.GetGeomType()

        ogr.RegisterAll()
        new_layer = ds.CreateLayer(layer_name, layer.GetSpatialRef(),
                                   geom_type, options)
        for x in range(layer.GetLayerDefn().GetFieldCount()):
            new_layer.CreateField(layer.GetLayerDefn().GetFieldDefn(x))

        layer.ResetReading()
        new_layer.StartTransaction()
        for fid in tqdm(range(layer.GetFeatureCount())):
            #try:
            new_feature = layer.GetFeature(fid)
            new_feature.SetFID(-1)
            new_layer.CreateFeature(new_feature)
            if fid % 128 == 0:
                new_layer.CommitTransaction()
                new_layer.StartTransaction()
        #except Exception as e:
        #    print("Got exception", e, "skipping feature")

        new_layer.CommitTransaction()

    except Exception as e:
        print("Got exception", e, "trying copy layer")

        new_layer = ds.CopyLayer(layer, layer_name, options)

    finally:
        if new_layer.GetFeatureCount() == 0:
            raise ValueError("Postgres vector feature count is 0")
        new_layer = None
Exemplo n.º 7
0
    def writeVectorFile(self, scaledPredPolygons):
        """
        将带有地理信息的多边形对象列表,转化为矢量文件并保存
        :param scaledPredPolygons: list 类型。带有地理信息的多边形对象列表
        :return:
        """
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
        gdal.SetConfigOption("SHAPE_ENCODING", "")

        strVectorFile = self.outPath

        ogr.RegisterAll()

        strDriverName = "ESRI Shapefile"
        oDriver = ogr.GetDriverByName(strDriverName)
        if oDriver is None:
            print("%s 驱动不可用!\n", strDriverName)

        oDS = oDriver.CreateDataSource(strVectorFile)
        if oDS is None:
            print("创建文件【%s】失败!", strVectorFile)

        papszLCO = []
        oLayer = oDS.CreateLayer("TestPolygon", None, ogr.wkbPolygon, papszLCO)
        if oLayer is None:
            print("图层创建失败!\n")

        oFieldID = ogr.FieldDefn("FieldID", ogr.OFTInteger)
        oLayer.CreateField(oFieldID, 1)

        oFieldName = ogr.FieldDefn("FieldName", ogr.OFTString)
        oFieldName.SetWidth(100)
        oLayer.CreateField(oFieldName, 1)

        oDefn = oLayer.GetLayerDefn()

        i = 0
        for poly in scaledPredPolygons:
            oFeatureTriangle = ogr.Feature(oDefn)
            oFeatureTriangle.SetField(0, i)
            oFeatureTriangle.SetField(1, "bianhua")
            geomTriangle = ogr.CreateGeometryFromWkt(poly.to_wkt())
            oFeatureTriangle.SetGeometry(geomTriangle)
            oLayer.CreateFeature(oFeatureTriangle)
            i = i + 1

        oDS.Destroy()
        print("数据集创建完成!")
Exemplo n.º 8
0
def dissolve_polygons(f_merged, f_ref, f_final):
    ref_merge = GS.geo_shape.open(f_merged)
    lyr_merge = ref_merge.get_layer(0)
    proj_in = lyr_merge.spatial_ref

    ref_ref = GS.geo_shape.open(f_ref)
    lyr_ref = ref_ref.get_layer(0)

    #---- create new
    ogr.RegisterAll()
    driver = ogr.GetDriverByName("ESRI Shapefile")
    if os.access(f_final, os.F_OK):
        driver.DeleteDataSource(f_final)

    ds_out = driver.CreateDataSource(f_final)
    layer_out = ds_out.CopyLayer(lyr_ref.layer, 'dissolved')

    dic_merge_cn = sub__index_feature_by_field(lyr_merge)
    dic_ref_cn = sub__index_feature_by_field(lyr_ref)

    ks = dic_merge_cn.keys()
    ks.sort()
    for k in ks:
        ls_i = dic_merge_cn[k]
        print k, len(ls_i)
        i_ft = ls_i.pop(0)

        ft_mgs = lyr_merge.layer.GetFeature(i_ft)
        geom_dsv = ft_mgs.GetGeometryRef()
        while ls_i:
            i_ft = ls_i.pop(0)
            ft_mg = lyr_merge.layer.GetFeature(i_ft)
            geom_mg = ft_mg.GetGeometryRef()
            geom_dsv = geom_dsv.Union(geom_mg)
            ft_mg.Destroy()

        i_ft_ref = dic_ref_cn[k]
        ft_out = layer_out.GetFeature(i_ft_ref[0])
        ft_out.SetGeometry(geom_dsv)
        layer_out.SetFeature(ft_out)

        ft_mgs.Destroy()
        ft_out.Destroy()

    ds_out.Destroy()
    '''
Exemplo n.º 9
0
def shp2txt(jpgFile, annFile):
    ogr.RegisterAll()

    image = cv2.imread(jpgFile)
    height, width = image.shape[:2]

    dataSource = ogr.Open(annFile)
    daLayer = dataSource.GetLayer(0)
    featureCount = daLayer.GetFeatureCount()

    msgs = []
    for _ in range(featureCount):
        feature = daLayer.GetNextFeature()

        geometry = feature.GetGeometryRef()
        if geometry == None:
            continue

        ring = geometry.GetGeometryRef(0)
        numPoints = ring.GetPointCount()
        if numPoints < 4:
            continue
        msg = []
        points = []
        for j in range(numPoints - 1):
            dcol, drow = ring.GetX(j), abs(ring.GetY(j))

            dcol = max(min(dcol, width - 1), 0)
            drow = max(min(drow, height - 1), 0)
            msg.append(str(dcol))
            msg.append(str(drow))
            points.append([dcol, drow])

        points = np.array(points).reshape(-1, 2)
        min_x, min_y = np.min(points, axis=0)
        max_x, max_y = np.max(points, axis=0)

        if msg and max_y - min_y > min_box_size and max_x - min_x > min_box_size:
            msgs.append(' '.join(msg))
    return msgs
Exemplo n.º 10
0
def txt2shp(in_txt, out_shp, field_name):

    # 生成shp
    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
    gdal.SetConfigOption("SHAPE_ENCODING", "")

    ogr.RegisterAll()
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds = driver.CreateDataSource(out_shp)

    # 创建shp的坐标系
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    layer = ds.CreateLayer("PointLayer", srs, ogr.wkbPoint)

    # 创建属性表字段
    field_value = ogr.FieldDefn(field_name, ogr.OFTReal)
    # 对layer对象添加字段
    layer.CreateField(field_value)

    # 打开txt按行创建feature
    with open(in_txt, 'r') as f:
        header = f.readline()
        for line in f.readlines():
            line_content = line.strip('\n')
            lat = line_content.split(' ')[0]
            lon = line_content.split(' ')[1]
            tem_avg = line_content.split(' ')[2]

            # 创建feature
            feature = ogr.Feature(layer.GetLayerDefn())
            # 设置feature属性值
            feature.SetField(field_name, tem_avg)
            # 编辑该feature的wkt字符串
            wkt = 'POINT({0} {1})'.format(lon, lat)
            # 根据wkt创建feature
            feature.SetGeometry(ogr.CreateGeometryFromWkt(wkt))
            # 将feature添加到layer中
            layer.CreateFeature(feature)
Exemplo n.º 11
0
    def prj2geo(shp_path, x, y):
        """输入为待操作shp的路径,和一组待转换的投影坐标"""
        # 为了支持中文路径,请添加下面这句代码
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
        # 为了使属性表字段支持中文,请添加下面这句
        gdal.SetConfigOption("SHAPE_ENCODING", "")
        # 注册所有的驱动
        ogr.RegisterAll()
        # 数据格式的驱动
        driver = ogr.GetDriverByName('ESRI Shapefile')
        ds = driver.Open(shp_path)
        layer0 = ds.GetLayerByIndex(0)

        # 或取到shp的投影坐标系信息
        prosrs = layer0.GetSpatialRef()
        geosrs = osr.SpatialReference()
        # 设置输出坐标系为WGS84
        geosrs.SetWellKnownGeogCS("WGS84")

        ct = osr.CoordinateTransformation(prosrs, geosrs)
        coords = ct.TransformPoint(x, y)
        # 输出为转换好的经纬度
        return coords[:2]
Exemplo n.º 12
0
def Excel2Shp(path,ExcelName,shpfilename,Lng_columns_num,Lat_columns_num):
    # 为了支持中文路径,请添加下面这句代码
    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","NO")
    # 为了使属性表字段支持中文,请添加下面这句
    gdal.SetConfigOption("SHAPE_ENCODING","GB2312")
    # 注册所有的驱动
    ogr.RegisterAll()
    #创建输出shp
    driver = ogr.GetDriverByName('ESRI Shapefile')
    os.chdir(path)
    if os.path.exists(shpfilename):
        driver.DeleteDataSource(shpfilename)
    outds = driver.CreateDataSource(shpfilename)
    if outds == None:
        print('创建文件失败!')
    #创建图层
    dst_osr = osr.SpatialReference()
    dst_osr.ImportFromEPSG(4326)
    #获取文件名,不包含扩展名
    layername = os.path.splitext(shpfilename)[0]
    print('layername:=='+layername)
    outlayer = outds.CreateLayer(layername,dst_osr,geom_type = ogr.wkbPoint)
    #获取EXCEL表头及数据
    columns,data=readExcelbyFileNameAndSheetName(ExcelName,'Sheet1')
    #获取表头个数
    columns_count = len(columns)
    #print('columns_count==='+str(columns_count))

    #--------------------------创建属性表字段----------------------------------------
    #遍历所有表头并创建属性表字段
    for i in range(columns_count):
        FieldName = columns[i]
        #print('FieldName==='+FieldName)

        #设置字段属性
        fieldDefn = ogr.FieldDefn(FieldName,ogr.OFTString)
        fieldDefn.SetWidth(100)
        #图层创建属性
        outlayer.CreateField(fieldDefn)

    #---------------------------创建要素-----------------------------------------------
    #读取要素统一属性
    featuredefn = outlayer.GetLayerDefn()

    #获取数据行数
    rows_count = len(data)
    print('rows_count==='+str(rows_count))

    #遍历所有数据行并将数据填写到shp字段中
    for row in range(rows_count):
        #获取每一行的X坐标WGS84_Lng,这里的参数是固定的,应该把参数分离出去,写活,
        # #否则换个表,如果存经纬度字段的变了顺序,就会出错
        point_x=float(data[row][Lng_columns_num-1])
        #print('point_x==='+str(point_x))
        #获取每一行的Y坐标WGS84_Lat
        point_y=float(data[row][Lat_columns_num-1])
        #print('point_y==='+str(point_y))

        # 创建点要素
        oFeaturePoint = ogr.Feature(featuredefn)
        #---------------------------给所有点要素的属性一一对应进行赋值-----------------
        #遍历所有列,给所有点要素的属性一一对应进行赋值
        for column in range(columns_count):
            #列名:即字段名,这里应该读取SHP的字段名,不能用EXCEL表头,可能会有创建字段时因为字段名太长而丢失完整字段名
            FieldName = columns[column]
            #print('FieldName==='+FieldName)
            #每个cell的数据值
            FieldValue = data[row][column]
            #print('FieldValue==='+str(FieldValue))
            #给各字段赋值
            oFeaturePoint.SetField(FieldName, FieldValue)

        #定义矢量要素为点
        geomPoint = ogr.Geometry(ogr.wkbPoint)
        #定义点的X,Y坐标值
        geomPoint.AddPoint(point_x,point_y)
        #给要素设置几何点信息
        oFeaturePoint.SetGeometry(geomPoint)
        #创建要素
        outlayer.CreateFeature(oFeaturePoint)

    outds.Destroy()
    print('数据集生成成功')
Exemplo n.º 13
0
    def write_shp(self, label):
        """
        --convert the pixel location to latitude and longitude
        --write all objects in a certain image into a single shp file
        """
        shapefilename = os.path.join(
            self.outputFolder_Path,
            get_filename(self.inputFile_Path, is_suffix=False) +
            '_%s_shp.shp' % self.class_names[label])
        class_bndbox = self.run_info['bndboxes']

        # 获取图像六元数 0-经度 1-经度分辨率 3-纬度 5-纬度分辨率
        lat_lon_init = get_geoTransform(self.inputFile_Path)

        # 注册所有的驱动
        ogr.RegisterAll()

        # 创建数据
        strDriverName = 'ESRI Shapefile'
        oDriver = ogr.GetDriverByName(strDriverName)
        if oDriver == None:
            print("%s 驱动不可用!\n", strDriverName)

        # 创建数据源
        oDS = oDriver.CreateDataSource(shapefilename)
        if oDS == None:
            print("创建文件【%s】失败!", shapefilename)

        # 创建图层
        outLayer = oDS.CreateLayer('detection', geom_type=ogr.wkbPolygon)
        # papszLCO = []
        # outLayer = oDS.CreateLayer("TestPolygon", None, ogr.wkbPolygon, papszLCO)

        # oDefn = outLayer.GetLayerDefn()
        # # 创建矩形要素
        # oFeatureRectangle = ogr.Feature(oDefn)
        # oFeatureRectangle.SetField(0, 1)
        # oFeatureRectangle.SetField(1, "rect1")
        # geomRectangle = ogr.CreateGeometryFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))")
        # oFeatureRectangle.SetGeometry(geomRectangle)
        # outLayer.CreateFeature(oFeatureRectangle)

        # create fields

        fieldDefn2 = ogr.FieldDefn('class', ogr.OFTInteger)
        fieldDefn2.SetWidth(10)
        outLayer.CreateField(fieldDefn2, 1)

        # get feature defintion
        outFeatureDefn = outLayer.GetLayerDefn()

        for object in class_bndbox:

            # wkt = "POINT(%f %f)" % (float(pointListX[i]), float(pointListY[i]))
            # point = ogr.CreateGeometryFromWkt(wkt)
            # outFeature.SetGeometry(point)

            if self.class_names.index(object[0]) != label:
                continue
            # 坐标转换
            Ymin = object[1] * lat_lon_init[5] + lat_lon_init[3]
            Xmin = object[2] * lat_lon_init[1] + lat_lon_init[0]
            Ymax = object[3] * lat_lon_init[5] + lat_lon_init[3]
            Xmax = object[4] * lat_lon_init[1] + lat_lon_init[0]

            oFeatureRectancle = ogr.Feature(outFeatureDefn)
            oFeatureRectancle.SetField(0,
                                       self.class_names.index(object[0]) + 1)
            polygon_cmd = 'POLYGON ((%f %f,%f %f,%f %f,%f %f,%f %f))' % (
                Xmin, Ymin, Xmin, Ymax, Xmax, Ymax, Xmax, Ymin, Xmin, Ymin)
            geomRectancle = ogr.CreateGeometryFromWkt(polygon_cmd)
            oFeatureRectancle.SetGeometry(geomRectancle)

            outLayer.CreateFeature(oFeatureRectancle)
            oFeatureRectancle.Destroy()

        oDS.Destroy()

        print('shp finished!')
        pass
Exemplo n.º 14
0
def testLoad(serverDS, table, sourceFile):
    ogr.RegisterAll()
    shapeDS = ogr.Open(sourceFile)
    sourceLayer = shapeDS.GetLayerByIndex(0)
    options = []
    name = serverDS.CopyLayer(sourceLayer, table, options).GetName()
Exemplo n.º 15
0
import ogr
import osr
import gdal

# 实现ArcToolBox - Analysis Tools - Overlay - Identity

if __name__ == '__main__':

    shp1 = r'H:\black_water\GF2_PMS2_L2_20210620104359_1_159_1002\river.shp'
    shp2 = r'H:\black_water\GF2_PMS2_L2_20210620104359_1_159_1002\temp\heichou.shp'

    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")  # 为了支持中文路径,请添加
    gdal.SetConfigOption("SHAPE_ENCODING", "UTF-8")  # 为了使属性表字段支持中文,请添加
    ogr.RegisterAll()  # 注册所有的驱动
    driver = ogr.GetDriverByName("ESRI Shapefile")  # 数据格式的驱动

    # 打开第一个shp获取图层数据
    ds1 = driver.Open(shp1)
    layer1 = ds1.GetLayer(0)

    # 打开第二个shp获取图层数据
    ds2 = driver.Open(shp2)
    layer2 = ds2.GetLayer(0)

    # 创建结果文件
    save_shp_path = r"H:\black_water\GF2_PMS2_L2_20210620104359_1_159_1002\identity.shp"
    oDS = driver.CreateDataSource(save_shp_path)
    # 创建坐标投影对象
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    # 创建结果图层
Exemplo n.º 16
0
    def write_shp(self):
        """
        --convert the pixel location to latitude and longitude
        --write all objects in a certain image into a single shp file
        """
        print('\n')
        print("Write shp files")
        pbar = tqdm.tqdm(total=len(self.input_img_list))
        for img_file in self.input_img_list:
            pbar.update(1)
            img_name = os.path.splitext(os.path.basename(img_file))[0]
            for label in (range(len(self.class_names))):
                shape_filename = os.path.join(
                    self.outputFolder_Path, img_name,
                    '%s_%s_shp.shp' % (img_name, self.class_names[label]))
                class_bndbox = self.run_info['bndboxes'][img_name]

                # 获取图像六元数 0-经度 1-经度分辨率 3-纬度 5-纬度分辨率
                lat_lon_init = gdal_utils.get_geotransform(img_file)

                # 注册所有的驱动
                ogr.RegisterAll()
                # 创建数据
                strDriverName = 'ESRI Shapefile'
                oDriver = ogr.GetDriverByName(strDriverName)
                if oDriver == None:
                    print("%s 驱动不可用!\n", strDriverName)

                # 创建数据源
                oDS = oDriver.CreateDataSource(shape_filename)
                if oDS == None:
                    print("创建文件【%s】失败!", shape_filename)

                # 创建图层
                outLayer = oDS.CreateLayer('detection',
                                           geom_type=ogr.wkbPolygon)
                fieldDefn2 = ogr.FieldDefn('class', ogr.OFTInteger)
                fieldDefn2.SetWidth(10)
                outLayer.CreateField(fieldDefn2, 1)
                # get feature defintion
                outFeatureDefn = outLayer.GetLayerDefn()
                for object in class_bndbox:
                    if self.class_names.index(object[0]) != label:
                        continue
                    # 坐标转换
                    Ymin = object[1] * lat_lon_init[5] + lat_lon_init[3]
                    Xmin = object[2] * lat_lon_init[1] + lat_lon_init[0]
                    Ymax = object[3] * lat_lon_init[5] + lat_lon_init[3]
                    Xmax = object[4] * lat_lon_init[1] + lat_lon_init[0]

                    oFeatureRectancle = ogr.Feature(outFeatureDefn)
                    oFeatureRectancle.SetField(
                        0,
                        self.class_names.index(object[0]) + 1)
                    polygon_cmd = 'POLYGON ((%f %f,%f %f,%f %f,%f %f,%f %f))' % (
                        Xmin, Ymin, Xmin, Ymax, Xmax, Ymax, Xmax, Ymin, Xmin,
                        Ymin)
                    geomRectancle = ogr.CreateGeometryFromWkt(polygon_cmd)
                    oFeatureRectancle.SetGeometry(geomRectancle)
                    outLayer.CreateFeature(oFeatureRectancle)
                    oFeatureRectancle.Destroy()

                oDS.Destroy()
        pbar.close()
        print('\n')
        print('shp finished!')
Exemplo n.º 17
0
def dissolve_polygons_shp(f_merged,f_ref,dic_ui_wopr,f_dislv):
	ref_merge = GS.geo_shape.open(f_merged)
	lyr_merge = ref_merge.get_layer(0)
	proj_in = lyr_merge.spatial_ref

	ref_ref = GS.geo_shape.open(f_ref)
	lyr_ref = ref_ref.get_layer(0)
	
	#dic_ui_area = index_area_by_ui(f_ref,'Code_uniq')

	#---- create new
	ogr.RegisterAll()
	driver = ogr.GetDriverByName("ESRI Shapefile")
	if os.access(f_dislv, os.F_OK):
		driver.DeleteDataSource(f_dislv)
		
	ds_out = driver.CreateDataSource(f_dislv)
	layer_out = ds_out.CreateLayer("dissolved", srs = proj_in)

	dfn_layer,ls_fields = sub__resotre_fields(lyr_ref,layer_out)

	dic_merge_cn = sub__index_feature_by_field(lyr_merge)
	dic_ref_cn = sub__index_feature_by_field(lyr_ref)

	ks = dic_merge_cn.keys()
	ks.sort()
	for k in ks:
		ls_i = dic_merge_cn[k]
		#print k,len(ls_i)
		#==== screen geom from unwanted pathrow
		if dic_ui_wopr[k][0] == 'within':
			ls_i = sub__screen_pr_for_within(ls_i,lyr_merge,dic_ui_wopr,k)
		
		
		#==== /screen
		if len(ls_i) <> 0:
			i_ft = ls_i.pop(0)
		else:
			continue
		
		#---- dissolve
		ft_mgs = lyr_merge.layer.GetFeature(i_ft)
		geom_dsv = ft_mgs.GetGeometryRef()

		i_max = i_ft
		area_max = 0.0
		while ls_i:
			i_ft = ls_i.pop(0)
			ft_mg = lyr_merge.layer.GetFeature(i_ft)
			geom_mg = ft_mg.GetGeometryRef()

			if not geom_mg.IsValid(): 
				geom_mg = geom_mg.Buffer(0.0)
				print 'fixing geom at ui =',k
			r_area = geom_mg.Area()
			if area_max < r_area:
				i_max = i_ft
				area_max = r_area
			geom_dsv = geom_dsv.Union(geom_mg)

			ft_mg.Destroy()
		#---- make new feature(geometry, field)
		ft_out = ogr.Feature(dfn_layer)
		ft_out.SetGeometry(geom_dsv)

		r_area = geom_dsv.Area() / 1000000.0
		r_perimeter = geom_dsv.Boundary().Length() / 1000.0
		
		i_ft_ref = dic_ref_cn[k]
		ft_ref = lyr_ref.layer.GetFeature(i_ft_ref[0])
		ft_mg_tmp = lyr_merge.layer.GetFeature(i_max)
		for fd in ls_fields:
			if fd == 'Area':
				cnt_fd = r_area
			elif fd == 'Perimeter':
				cnt_fd = r_perimeter
			elif fd in ['PathRow','Day','Source']:
				cnt_fd = ft_mg_tmp.GetField(fd)
			else:
				cnt_fd = ft_ref.GetField(fd)
			ft_out.SetField(fd, cnt_fd)
		ft_mg_tmp.Destroy()
		layer_out.CreateFeature(ft_out)

		ft_mgs.Destroy()
		ft_out.Destroy()

	ds_out.Destroy()
Exemplo n.º 18
0
# coding=gbk
import ogr, os
from osgeo import gdal

#chinese directory support
gdal.SetConfigOption('GDAL_FILENAME_IS_UTF8', 'NO')
#chinese attribute list support
gdal.SetConfigOption('SHAPE_ENCODING', '')
#register
ogr.RegisterAll()


def point_to_shp(inputlist, outSHPfn):
    # print(outSHPfn)
    # exit()
    fieldType = ogr.OFTString
    # Create the output shapefile
    shpDriver = ogr.GetDriverByName("ESRI Shapefile")
    if os.path.exists(outSHPfn):
        shpDriver.DeleteDataSource(outSHPfn)
    outDataSource = shpDriver.CreateDataSource(outSHPfn)
    outLayer = outDataSource.CreateLayer(outSHPfn, geom_type=ogr.wkbPoint)

    # create a field
    idField1 = ogr.FieldDefn('val1', fieldType)
    idField2 = ogr.FieldDefn('val2', fieldType)
    idField3 = ogr.FieldDefn('val3', fieldType)
    idField4 = ogr.FieldDefn('val4', fieldType)
    idField5 = ogr.FieldDefn('val5', fieldType)

    outLayer.CreateField(idField1)
Exemplo n.º 19
0
def transitionMatrix(shpPath):
    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")  # 为了支持中文路径,请添加
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")  # 为了使属性表字段支持中文,请添加
    ogr.RegisterAll()  # 注册所有的驱动

    ds = ogr.Open(shpPath, gdal.GA_ReadOnly)
    layer = ds.GetLayer(0)
    result = {
        '1-1': 0,
        '1-2': 0,
        '1-3': 0,
        '1-4': 0,
        '1-5': 0,
        '1-6': 0,
        '2-1': 0,
        '2-2': 0,
        '2-3': 0,
        '2-4': 0,
        '2-5': 0,
        '2-6': 0,
        '3-1': 0,
        '3-2': 0,
        '3-3': 0,
        '3-4': 0,
        '3-5': 0,
        '3-6': 0,
        '4-1': 0,
        '4-2': 0,
        '4-3': 0,
        '4-4': 0,
        '4-5': 0,
        '4-6': 0,
        '5-1': 0,
        '5-2': 0,
        '5-3': 0,
        '5-4': 0,
        '5-5': 0,
        '5-6': 0,
        '6-1': 0,
        '6-2': 0,
        '6-3': 0,
        '6-4': 0,
        '6-5': 0,
        '6-6': 0
    }

    for i in range(layer.GetFeatureCount()):
        feature = layer.GetFeature(i)
        level_old = feature.GetField('level_2016')
        level_new = feature.GetField('level_2020')
        area = feature.GetField('shape_area')
        keyStr = str(level_old) + '-' + str(level_new)
        result[keyStr] += area

    dfDict = {}
    for i in range(1, 7):
        tempList = []
        for j in range(1, 7):
            keyStr = str(j) + '-' + str(i)
            # print(keyStr)
            tempList.append(result[keyStr])
            dfDict[str(i)] = tempList
    resultDf = pd.DataFrame(dfDict)
    resultDf.rename(columns={
        '1': 'I',
        '2': 'II',
        '3': 'III',
        '4': 'IV',
        '5': 'V',
        '6': '劣V'
    },
                    inplace=True)
    resultDf.index = Series(['I', 'II', 'III', 'IV', 'V', '劣V'])
    resultDf[[
        'I', 'II', 'III', 'IV', 'V', '劣V'
    ]] = resultDf[['I', 'II', 'III', 'IV', 'V', '劣V']] / (1000 * 1000)
    return resultDf