def netcdf_27(): if gdaltest.netcdf_drv is None: return 'skip' #test default config test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4672) config_bak = gdal.GetConfigOption('GDAL_NETCDF_BOTTOMUP') gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', None) result = test.testOpen() gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', config_bak) if result != 'success': print('failed open without GDAL_NETCDF_BOTTOMUP') return result #test GDAL_NETCDF_BOTTOMUP=NO test = gdaltest.GDALTest('NETCDF', '../data/int16-nogeo.nc', 1, 4855) config_bak = gdal.GetConfigOption('GDAL_NETCDF_BOTTOMUP') gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', 'NO') result = test.testOpen() gdal.SetConfigOption('GDAL_NETCDF_BOTTOMUP', config_bak) if result != 'success': print('failed open with GDAL_NETCDF_BOTTOMUP') return result return 'success'
def aaigrid_10(): try: os.remove('data/float64.asc.aux.xml') except: pass gdal.SetConfigOption('AAIGRID_DATATYPE', 'Float64') ds = gdal.Open('data/float64.asc') gdal.SetConfigOption('AAIGRID_DATATYPE', None) if ds.GetRasterBand(1).DataType != gdal.GDT_Float64: gdaltest.post_reason('Data type is not Float64!') return 'fail' nv = ds.GetRasterBand(1).GetNoDataValue() if abs(nv - -1.234567890123) > 1e-16: gdaltest.post_reason('did not get expected nodata value') return 'fail' got_minmax = ds.GetRasterBand(1).ComputeRasterMinMax() if abs(got_minmax[0] - 1.234567890123) > 1e-16: gdaltest.post_reason('did not get expected min value') return 'fail' if abs(got_minmax[1] - 1.234567890123) > 1e-16: gdaltest.post_reason('did not get expected max value') return 'fail' try: os.remove('data/float64.asc.aux.xml') except: pass return 'success'
def ogr_gml_19(): if not gdaltest.have_gml_reader: return 'skip' try: os.remove('data/gnis_pop_110.gfs') except: pass gdal.SetConfigOption('GML_INVERT_AXIS_ORDER_IF_LAT_LONG', 'NO') ds = ogr.Open('data/gnis_pop_110.gml') gdal.SetConfigOption('GML_INVERT_AXIS_ORDER_IF_LAT_LONG', None) lyr = ds.GetLayer(0) sr = lyr.GetSpatialRef() got_wkt = sr.ExportToWkt() if got_wkt.find('GEOGCS["WGS 84"') == -1 or \ got_wkt.find('AXIS["Latitude",NORTH],AXIS["Longitude",EAST]') == -1: gdaltest.post_reason('did not get expected SRS') print(got_wkt) return 'fail' feat = lyr.GetNextFeature() geom = feat.GetGeometryRef() got_wkt = geom.ExportToWkt() if got_wkt != 'POINT (34.12 2.09)': gdaltest.post_reason('did not get expected geometry') print(got_wkt) return 'fail' return 'success'
def dted_8(): # this will enable DTED_VERIFY_CHECKSUM gdal.SetConfigOption('DTED_VERIFY_CHECKSUM', 'YES') ds = gdal.Open( 'data/n43_bad_crc.dt0' ) band = ds.GetRasterBand(1) # numerous errors would be reported gdal.PushErrorHandler( 'CPLQuietErrorHandler' ) chksum = band.Checksum() gdal.PopErrorHandler() gdal.SetConfigOption('DTED_VERIFY_CHECKSUM', 'NO') if gdal.GetLastErrorMsg() is None: gdaltest.post_reason( 'An expected warning was not emitted' ) return 'fail' # 49187 is the checksum of data is the DTED is read without checking its checksum # so we should not get this value if chksum == 49187: gdaltest.post_reason('DTED_VERIFY_CHECKSUM=YES has had no effect!') return 'fail' return 'success'
def ogr_gml_7(): if not gdaltest.have_gml_reader: return 'skip' gdal.SetConfigOption('GML_EXPOSE_FID', 'FALSE') gml_ds = ogr.Open('data/test_point.gml') gdal.SetConfigOption('GML_EXPOSE_FID', None) lyr = gml_ds.GetLayer() ldefn = lyr.GetLayerDefn() # Test fix for #2969 if lyr.GetFeatureCount() != 5: gdaltest.post_reason('Bad feature count') return 'fail' try: ldefn.GetFieldDefn(0).GetFieldTypeName except: return 'skip' if ldefn.GetFieldDefn(0).GetFieldTypeName(ldefn.GetFieldDefn(0).GetType())\ != 'Real': return 'fail' if ldefn.GetFieldDefn(1).GetFieldTypeName(ldefn.GetFieldDefn(1).GetType())\ != 'Integer': return 'fail' if ldefn.GetFieldDefn(2).GetFieldTypeName(ldefn.GetFieldDefn(2).GetType())\ != 'String': return 'fail' return 'success'
def ogr_gml_33(): if not gdaltest.have_gml_reader: return 'skip' # Test reading second layer and then first layer gdal.SetConfigOption('GML_READ_MODE', 'INTERLEAVED_LAYERS') ds = ogr.Open('data/testfmegml_interleaved.gml') gdal.SetConfigOption('GML_READ_MODE', None) read_sequence = [[0, 1], [0, None], [1, 3], [2, 5], [2, None], [0, 2], [1, 4], [1, None], [2, 6], [2, None], [0, None], [1, None], [2, None]] for i in range(len(read_sequence)): lyr = ds.GetLayer(read_sequence[i][0]) feat = lyr.GetNextFeature() if feat is None: fid = None else: fid = feat.GetFID() expected_fid = read_sequence[i][1] if fid != expected_fid: gdaltest.post_reason('failed at step %d' % i) return 'fail' return 'success'
def ogr_gml_31(): if not gdaltest.have_gml_reader: return 'skip' gdal.SetConfigOption('GML_READ_MODE', 'SEQUENTIAL_LAYERS') ret = ogr_gml_29() gdal.SetConfigOption('GML_READ_MODE', None) if ret != 'success': return ret # Test reading second layer and then first layer gdal.SetConfigOption('GML_READ_MODE', 'SEQUENTIAL_LAYERS') ds = ogr.Open('data/testfmegml.gml') gdal.SetConfigOption('GML_READ_MODE', None) lyr = ds.GetLayer(1) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() if feat.GetFID() != 1: gdaltest.post_reason( 'did not get feature when reading directly second layer') return 'fail' lyr = ds.GetLayer(0) feat = lyr.GetNextFeature() feat = lyr.GetNextFeature() if feat.GetFID() != 1: gdaltest.post_reason( 'did not get feature when reading back first layer') return 'fail' return 'success'
def wms_4(): if gdaltest.wms_drv is None or gdaltest.wms_ds is None: return 'skip' if not gdaltest.wms_srv1_ok: return 'skip' gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'ON') gdal.PushErrorHandler('CPLQuietErrorHandler') cs = gdaltest.wms_ds.GetRasterBand(1).Checksum(0, 0, 100, 100) gdal.PopErrorHandler() gdal.SetConfigOption('CPL_ACCUM_ERROR_MSG', 'OFF') msg = gdal.GetLastErrorMsg() gdal.ErrorReset() if msg is not None and msg.find( 'Service denied due to system overload') != -1: print(msg) return 'skip' if cs != 57182: gdaltest.post_reason('Wrong checksum: ' + str(cs)) return 'fail' return 'success'
def gml_Arc(): poslist_list = [ ("1 0 0 1 -1 0", 'LINESTRING (1 0,0.707106781186548 0.707106781186547,0.0 1.0,-0.707106781186547 0.707106781186548,-1.0 0.0)' ), ("1 0 0 -1 -1 0", 'LINESTRING (1 0,0.707106781186548 -0.707106781186547,0.0 -1.0,-0.707106781186547 -0.707106781186548,-1.0 -0.0)' ), ("1 0 -1 0 0 -1 ", 'LINESTRING (1 0,0.707106781186548 0.707106781186547,0.0 1.0,-0.707106781186547 0.707106781186548,-1.0 0.0,-0.707106781186548 -0.707106781186547,-0.0 -1.0)' ), ("1 0 -1 0 0 1 ", 'LINESTRING (1 0,0.707106781186548 -0.707106781186547,0.0 -1.0,-0.707106781186547 -0.707106781186548,-1.0 -0.0,-0.707106781186548 0.707106781186547,-0.0 1.0)' ), ("1 0 0 0 -1 0 ", 'LINESTRING (1 0,0 0,-1 0)' ), ("0 1 1 0 0 -1", 'LINESTRING (0.0 1.0,0.707106781186548 0.707106781186547,1 0,0.707106781186548 -0.707106781186547,0.0 -1.0)' ), ("0 1 -1 0 0 -1", 'LINESTRING (0.0 1.0,-0.707106781186547 0.707106781186548,-1.0 0.0,-0.707106781186548 -0.707106781186547,-0.0 -1.0)' ), ("-1 0 0 1 1 0", 'LINESTRING (-1.0 0.0,-0.707106781186547 0.707106781186548,0.0 1.0,0.707106781186548 0.707106781186547,1 0)' ), ("-1 0 0 1 -0.707106781186547 -0.707106781186548", 'LINESTRING (-1.0 0.0,-0.707106781186547 0.707106781186548,0.0 1.0,0.707106781186548 0.707106781186547,1 0,0.707106781186548 -0.707106781186547,0.0 -1.0,-0.707106781186547 -0.707106781186548)' ) ] for (poslist, expected_wkt) in poslist_list: gml = "<gml:Arc><gml:posList>%s</gml:posList></gml:Arc>" % poslist gdal.SetConfigOption('OGR_ARC_STEPSIZE','45') geom = ogr.CreateGeometryFromGML( gml ) gdal.SetConfigOption('OGR_ARC_STEPSIZE',None) if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) != 0: print(gml) print(geom) return 'fail' return 'success'
def ogr_s57_online_4(): if gdaltest.s57_ds is None: return 'skip' if not gdaltest.download_file('http://www1.kaiho.mlit.go.jp/KOKAI/ENC/images/sample/sample.zip', 'sample.zip'): return 'skip' try: os.stat('tmp/cache/ENC_ROOT/JP34NC94.000') except: try: gdaltest.unzip( 'tmp/cache', 'tmp/cache/sample.zip') try: os.stat('tmp/cache/ENC_ROOT/JP34NC94.000') except: return 'skip' except: return 'skip' gdal.SetConfigOption('OGR_S57_OPTIONS', 'RETURN_PRIMITIVES=ON,RETURN_LINKAGES=ON,LNAM_REFS=ON,RECODE_BY_DSSI=ON') ds = ogr.Open('tmp/cache/ENC_ROOT/JP34NC94.000') gdal.SetConfigOption('OGR_S57_OPTIONS', None) lyr = ds.GetLayerByName('LNDMRK') for feat in lyr: mystr = feat.NOBJNM if mystr and sys.version_info < (3,0,0): mystr.decode('UTF-8').encode('UTF-8') return 'success'
def gml_Circle(): gml = """<gml:PolygonPatch> <gml:exterior> <gml:Ring> <gml:curveMember> <gml:Curve> <gml:segments> <gml:Circle> <gml:posList>-1 0 0 1 -0.707106781186547 -0.707106781186548</gml:posList> </gml:Circle> </gml:segments> </gml:Curve> </gml:curveMember> </gml:Ring> </gml:exterior> </gml:PolygonPatch>""" gdal.SetConfigOption('OGR_ARC_STEPSIZE','45') geom = ogr.CreateGeometryFromGML( gml ) gdal.SetConfigOption('OGR_ARC_STEPSIZE',None) expected_wkt = 'POLYGON ((-1.0 0.0,-0.707106781186547 0.707106781186548,0.0 1.0,0.707106781186548 0.707106781186547,1 0,0.707106781186548 -0.707106781186547,0.0 -1.0,-0.707106781186547 -0.707106781186548,-1.0 -0.0,-1.0 -0.0))' if ogrtest.check_feature_geometry(geom, ogr.CreateGeometryFromWkt(expected_wkt)) != 0: print(geom) return 'fail' return 'success'
def mask_7(): if gdaltest.have_ng == 0: return 'skip' gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE') ds = gdal.Open('data/test3_with_1mask_1bit.tif') if ds is None: gdaltest.post_reason('Failed to open test dataset.') return 'fail' for i in (1, 2, 3): band = ds.GetRasterBand(i) if band.GetMaskFlags() != gdal.GMF_PER_DATASET: gdaltest.post_reason('Did not get expected mask.') return 'fail' cs = band.GetMaskBand().Checksum() if cs != 100: gdaltest.post_reason('Got wrong mask checksum') print(cs) return 'fail' gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE') return 'success'
def rpftoc_4(): gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'YES') shutil.copyfile('data/A.TOC', 'tmp/A.TOC') shutil.copyfile('data/RPFTOC01.ON2', 'tmp/RPFTOC01.ON2') ds = gdal.Open('NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:tmp/A.TOC') err = ds.BuildOverviews(overviewlist=[2, 4]) if err != 0: gdaltest.post_reason('BuildOverviews reports an error') return 'fail' if ds.GetRasterBand(1).GetOverviewCount() != 2: gdaltest.post_reason('Overview missing on target file.') return 'fail' ds = None ds = gdal.Open('NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:tmp/A.TOC') if ds.GetRasterBand(1).GetOverviewCount() != 2: gdaltest.post_reason('Overview missing on target file after re-open.') return 'fail' ds = None gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'NO') os.unlink('tmp/A.TOC') os.unlink('tmp/A.TOC.1.ovr') os.unlink('tmp/RPFTOC01.ON2') return 'success'
def hfa_write_bit2grayscale(): import shutil shutil.copyfile('data/small1bit.img', 'tmp/small1bit.img') shutil.copyfile('data/small1bit.rrd', 'tmp/small1bit.rrd') gdal.SetConfigOption('USE_RRD', 'YES') gdal.SetConfigOption('HFA_USE_RRD', 'YES') ds = gdal.Open('tmp/small1bit.img', gdal.GA_Update) ds.BuildOverviews(resampling='average_bit2grayscale', overviewlist=[2]) ov = ds.GetRasterBand(1).GetOverview(1) if ov.Checksum() != 57325: gdaltest.post_reason('wrong checksum for greyscale overview.') return 'fail' ds = None gdal.GetDriverByName('HFA').Delete('tmp/small1bit.img') gdal.SetConfigOption('USE_RRD', 'NO') gdal.SetConfigOption('HFA_USE_RRD', 'NO') # as an aside, confirm the .rrd file was deleted. try: open('tmp/small1bit.rrd') gdaltest.post_reason('tmp/small1bit.rrd not deleted!') return 'fail' except: pass return 'success'
def dted_15(): gdal.SetConfigOption('GDAL_DTED_SINGLE_BLOCK', 'YES') tst = gdaltest.GDALTest('dted', 'n43.dt0', 1, 49187) ret = tst.testOpen() gdal.SetConfigOption('GDAL_DTED_SINGLE_BLOCK', None) return ret
def ogr_xlsx_6(): drv = ogr.GetDriverByName('XLSX') if drv is None: return 'skip' # In this dataset the column titles are not recognised by default. gdal.SetConfigOption('OGR_XLSX_HEADERS', 'FORCE') ds = ogr.Open('data/inlineStr.xlsx') lyr = ds.GetLayerByName('inlineStr') if lyr.GetFeatureCount() != 1: gdaltest.post_reason('fail') print(lyr.GetFeatureCount()) return 'fail' lyr.ResetReading() feat = lyr.GetNextFeature() if feat.Bl_District_t != 'text6': gdaltest.post_reason('Did not get expected value(1)') return 'fail' if abs(float(feat.GetField('Lat')) - 23.6247122) > 0.00001: gdaltest.post_reason('Did not get expected value(2)') return 'fail' gdal.SetConfigOption('OGR_XLSX_HEADERS', None) return 'success'
def jpeg_9(): gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'NO') ds = gdal.Open('data/rgb_ntf_cmyk.jpg') gdal.SetConfigOption('GDAL_JPEG_TO_RGB', 'YES') expected_cs = 21187 if ds.GetRasterBand(1).Checksum() != expected_cs: gdaltest.post_reason('Wrong checksum on copied image.') print(ds.GetRasterBand(1).Checksum()) return 'fail' if ds.GetRasterBand(1).GetRasterColorInterpretation() != gdal.GCI_CyanBand: gdaltest.post_reason('Wrong color interpretation.') print(ds.GetRasterBand(1).GetRasterColorInterpretation()) return 'fail' expected_cs = 21054 if ds.GetRasterBand(2).Checksum() != expected_cs: gdaltest.post_reason('Wrong checksum on copied image.') print(ds.GetRasterBand(2).Checksum()) return 'fail' if ds.GetRasterBand( 2).GetRasterColorInterpretation() != gdal.GCI_MagentaBand: gdaltest.post_reason('Wrong color interpretation.') print(ds.GetRasterBand(2).GetRasterColorInterpretation()) return 'fail' expected_cs = 21499 if ds.GetRasterBand(3).Checksum() != expected_cs: gdaltest.post_reason('Wrong checksum on copied image.') print(ds.GetRasterBand(3).Checksum()) return 'fail' if ds.GetRasterBand( 3).GetRasterColorInterpretation() != gdal.GCI_YellowBand: gdaltest.post_reason('Wrong color interpretation.') print(ds.GetRasterBand(3).GetRasterColorInterpretation()) return 'fail' expected_cs = 21069 if ds.GetRasterBand(4).Checksum() != expected_cs: gdaltest.post_reason('Wrong checksum on copied image.') print(ds.GetRasterBand(4).Checksum()) return 'fail' if ds.GetRasterBand( 4).GetRasterColorInterpretation() != gdal.GCI_BlackBand: gdaltest.post_reason('Wrong color interpretation.') print(ds.GetRasterBand(4).GetRasterColorInterpretation()) return 'fail' return 'success'
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")
def imagexy2shp(img_path, strVectorFile, bboxes, scores, clss, cls_dict): im_width, im_height, im_proj, im_geotrans, im_data, dataset = read_img( img_path) gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO") # 为了支持中文路径 gdal.SetConfigOption("SHAPE_ENCODING", "CP936") # 为了使属性表字段支持中文 ogr.RegisterAll() strDriverName = "ESRI Shapefile" # 创建数据,这里创建ESRI的shp文件 oDriver = ogr.GetDriverByName(strDriverName) if oDriver == None: print("%s 驱动不可用!\n", strDriverName) oDS = oDriver.CreateDataSource(strVectorFile) # 创建数据源 if oDS == None: print("创建文件【%s】失败!", strVectorFile) # srs = osr.SpatialReference() # 创建空间参考 # srs.ImportFromEPSG(4326) # 定义地理坐标系WGS1984 srs = osr.SpatialReference( wkt=dataset.GetProjection() ) #我在读栅格图的时候增加了输出dataset,这里就可以不用指定投影,实现全自动了,上面两行可以注释了,并且那个proj参数也可以去掉了,你们自己去掉吧 papszLCO = [] # 创建图层,创建一个多边形图层,"TestPolygon"->属性表名 oLayer = oDS.CreateLayer("TestPolygon", srs, ogr.wkbPolygon, papszLCO) if oLayer == None: print("图层创建失败!\n") '''下面添加矢量数据,属性表数据、矢量数据坐标''' oFieldID = ogr.FieldDefn("cls", ogr.OFTString) # 创建一个叫FieldID的整型属性 oLayer.CreateField(oFieldID, 1) oFieldID = ogr.FieldDefn("Confidence", ogr.OFTInteger) # 创建一个叫FieldID的整型属性 oLayer.CreateField(oFieldID, 1) # oFieldName = ogr.FieldDefn("FieldName", ogr.OFTString) # 创建一个叫FieldName的字符型属性 # oFieldName.SetWidth(100) # 定义字符长度为100 # oLayer.CreateField(oFieldName, 1) oDefn = oLayer.GetLayerDefn() # 定义要素 # 创建单个面 for bbox, score, cls in zip(bboxes, scores, clss): oFeatureTriangle = ogr.Feature(oDefn) oFeatureTriangle.SetField( 0, cls_dict[int(cls)]) # 第一个参数表示第几个字段,第二个参数表示字段的值 oFeatureTriangle.SetField(1, score) # oFeatureTriangle.SetField(1, "单个面") ring = ogr.Geometry(ogr.wkbLinearRing) # 构建几何类型:线 ring.AddPoint(bbox[0], bbox[1]) # 添加点01 ring.AddPoint(bbox[2], bbox[1]) # 添加点02 ring.AddPoint(bbox[2], bbox[3]) # 添加点03 ring.AddPoint(bbox[0], bbox[3]) # 添加点04 yard = ogr.Geometry(ogr.wkbPolygon) # 构建几何类型:多边形 yard.AddGeometry(ring) yard.CloseRings() geomTriangle = ogr.CreateGeometryFromWkt(str(yard)) # 将封闭后的多边形集添加到属性表 oFeatureTriangle.SetGeometry(geomTriangle) oLayer.CreateFeature(oFeatureTriangle) oDS.Destroy() print("数据集创建完成!\n")
def mask_12(): if gdaltest.have_ng == 0: return 'skip' gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'FALSE') ds = gdal.Open('data/test3_with_mask_1bit_and_ovr.tif') if ds is None: gdaltest.post_reason('Failed to open test dataset.') return 'fail' for i in (1, 2, 3): band = ds.GetRasterBand(i) # Let's fetch the mask if band.GetMaskFlags() != gdal.GMF_PER_DATASET: gdaltest.post_reason('Did not get expected mask.') return 'fail' cs = band.GetMaskBand().Checksum() if cs != 100: gdaltest.post_reason('Got wrong mask checksum') print(cs) return 'fail' # Let's fetch the overview band = ds.GetRasterBand(i).GetOverview(0) cs = band.Checksum() if cs != 1126: gdaltest.post_reason('Got wrong overview checksum') print(cs) return 'fail' # Let's fetch the mask of the overview if band.GetMaskFlags() != gdal.GMF_PER_DATASET: gdaltest.post_reason('Did not get expected mask.') return 'fail' cs = band.GetMaskBand().Checksum() if cs != 25: gdaltest.post_reason( 'Got wrong checksum for the mask of the overview') print(cs) return 'fail' # Let's fetch the overview of the mask == the mask of the overview band = ds.GetRasterBand(i).GetMaskBand().GetOverview(0) cs = band.Checksum() if cs != 25: gdaltest.post_reason( 'Got wrong checksum for the overview of the mask') print(cs) return 'fail' gdal.SetConfigOption('GDAL_TIFF_INTERNAL_MASK_TO_8BIT', 'TRUE') return 'success'
def set_log_config(location, name="log"): path = os.path.join(location, name) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(message)s", filename=path + ".log", level=logging.DEBUG, ) gdal.SetConfigOption("CPL_LOG_ERRORS", path + "_gdal_err.log") gdal.SetConfigOption("CPL_LOG", path + "_gdal.log")
def createPoint(point_json, shp_name, field): ''' 生成点shp文件 输入: point_json:描述点的geojson文件 name:要生成的shp文件名 field:shp文件中的字段名及数据类型 {字段1:类型1,字段2:类型2,字段3:类型3} 常见数据类型:ogr.OFTString ogr.OFTReal ogr.OFTInteger ''' # 设置shapefile驱动 gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES") gdal.SetConfigOption("SHAPE_ENCODING", "gbk") driver = ogr.GetDriverByName("ESRI Shapefile") # 创建数据源 data_source = driver.CreateDataSource(shp_name) # 创建空间参考,WGS84 srs = osr.SpatialReference() srs.ImportFromEPSG(4326) # 创建图层 layer = data_source.CreateLayer("point", srs, ogr.wkbPoint) # 带坐标系文件 # 设置字段 for field_name, field_type in field.items(): if len(field_name) > 10: fn = ogr.FieldDefn(field_name[0:10], field_type) else: fn = ogr.FieldDefn(field_name, field_type) #数据类型为str时,设置字段长度 if field_type == ogr.OFTString: fn.SetWidth(128) layer.CreateField(fn) for point in point_json['features']: # 创建特征 feature = ogr.Feature(layer.GetLayerDefn()) # 和设置字段内容进行关联 ,从数据源中写入数据 for field_name, _ in field.items(): if len(field_name) > 10: feature.SetField(field_name[0:10], point['properties'][field_name]) else: feature.SetField(field_name, point['properties'][field_name]) # 生成点坐标 point_geo = ogr.CreateGeometryFromJson(str(point['geometry'])) feature.SetGeometry(point_geo) # 添加点 layer.CreateFeature(feature) # 关闭 特征 feature = None # 关闭数据 data_source = None
def ChangeToJson(vector, output): print("Starting........") #打开矢量图层 gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES") gdal.SetConfigOption("SHAPE_ENCODING", "GBK") shp_ds = ogr.Open(vector) shp_lyr = shp_ds.GetLayer(0) numFeatures = shp_lyr.GetFeatureCount() print("Features number:{}".format(numFeatures)) # 获取范围 extent = shp_lyr.GetExtent() print("Extent:", extent) print("UL:", extent[0], extent[3]) print("LR:", extent[1], extent[2]) # 循环每个要素属性 for i in range(numFeatures): feature = shp_lyr.GetNextFeature() # 获取字段“id”的属性 # id = feature.GetField('type') # 获取空间属性 # print(id) geometry = feature.GetGeometryRef() # x = geometry.GetX() polygonextent = geometry.GetEnvelope() print(geometry.GetEnvelope()) # print(y) # y = geometry.GetY() print("UL:", polygonextent[0], polygonextent[3]) print("LR:", polygonextent[1], polygonextent[2]) print("segmentation:", geometry) # # 创建结果Geojson # baseName = os.path.basename(output) # out_driver = ogr.GetDriverByName('GeoJSON') # out_ds = out_driver.CreateDataSource(output) # if out_ds.GetLayer(baseName): # out_ds.DeleteLayer(baseName) # out_lyr = out_ds.CreateLayer(baseName, shp_lyr.GetSpatialRef()) # out_lyr.CreateFields(shp_lyr.schema) # out_feat = ogr.Feature(out_lyr.GetLayerDefn()) # # #生成结果文件 # for feature in shp_lyr: # out_feat.SetGeometry(feature.geometry()) # for j in range(feature.GetFieldCount()): # out_feat.SetField(j, feature.GetField(j)) # out_lyr.CreateFeature(out_feat) # # del out_ds # del shp_ds print("Success........")
def rpftoc_2(): gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'YES') tst = gdaltest.GDALTest( 'RPFTOC', 'NITF_TOC_ENTRY:CADRG_ONC_1,000,000_2_0:data/A.TOC', 1, 0, filename_absolute=1) res = tst.testOpen() gdal.SetConfigOption('RPFTOC_FORCE_RGBA', 'NO') return res
def ogr_osm_9(): if ogrtest.osm_drv is None: return 'skip' old_val = gdal.GetConfigOption('OSM_USE_CUSTOM_INDEXING') gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', 'NO') ret = ogr_osm_8() gdal.SetConfigOption('OSM_USE_CUSTOM_INDEXING', old_val) return ret
def setup_logging(approot, config=None): """ Setup the roam logger relative to the given approot folder. :param approot: The folder to create the log folder in. """ if config is None: config = {"loglevel": "INFO"} try: logpath = os.path.join(os.environ['ROAM_APPPATH'], 'log') except KeyError: logpath = os.path.join(approot, 'log') print "Logging into: {}".format(logpath) if not os.path.exists(logpath): os.makedirs(logpath) LOG_FILENAME = os.path.join(logpath, "{}_roam.log".format(getpass.getuser())) log_format = '%(levelname)s - %(asctime)s - %(module)s-%(funcName)s:%(lineno)d - %(message)s' console_format = '%(levelname)s %(module)s-%(funcName)s:%(lineno)d - %(message)s' formater = logging.Formatter(log_format) console_formater = logging.Formatter(console_format) filehandler = handlers.RotatingFileHandler(LOG_FILENAME, mode='at', maxBytes=1000000, backupCount=5) levelname = config.get("loglevel", "INFO") level = logging.getLevelName(levelname) filehandler.setLevel(level) filehandler.setFormatter(formater) stream = logging.StreamHandler(stream=sys.stdout) stream.setLevel(logging.DEBUG) stream.setFormatter(console_formater) logger.handlers = [] logger.addHandler(stream) logger.addHandler(filehandler) logger.setLevel(logging.DEBUG) uic.uiparser.logger.setLevel(logging.INFO) uic.properties.logger.setLevel(logging.INFO) if levelname == "DEBUG": gdal.SetConfigOption("CPL_LOG", os.path.join(logpath, "gdallog.log")) gdal.SetConfigOption("CPL_DEBUG", "ON") else: gdal.SetConfigOption("CPL_LOG", "") gdal.SetConfigOption("CPL_DEBUG", "OFF") faulthandler.enable(file=open(os.path.join(logpath, "crashlog.log"), 'w'))
def create_dem(self, dem_files): dem_files = list(dem_files.values()) output_folder = os.path.dirname(dem_files[0]) dem_src = os.path.join( output_folder, f'Copernicus_{self.mgrs_tile}_{self.resolution}_mosaic.tif') LOGGER.info('Creating DEM mosaic...') no_data = -20000 try: # Mosaic if self.cross_dateline: gdal.SetConfigOption('CENTER_LONG', '180') options = gdal.WarpOptions(dstNodata=no_data, outputType=gdal.GDT_Int16, dstSRS='EPSG:4326') ds = gdal.Warp(dem_src, dem_files, options=options) # Replace no-data by 0 dem_band = ds.GetRasterBand(1) dem_arr = dem_band.ReadAsArray() dem_arr[dem_arr == no_data] = 0 dem_band.WriteArray(dem_arr) dem_band.FlushCache() ds = None gdal.SetConfigOption('CENTER_LONG', '0') LOGGER.debug('DEM mosaic: {}'.format(dem_src)) except Exception as e: LOGGER.fatal(e, exc_info=True) LOGGER.fatal('error using gdalwarp') else: # Crop and reproject LOGGER.info('Cropping and projecting DEM...') extent = self.extent(True) os.makedirs(os.path.dirname(self.dem_output), exist_ok=True) options = gdal.WarpOptions(dstSRS=self.hcs_code, xRes=self.resolution, yRes=self.resolution, resampleAlg='cubicspline', outputType=gdal.GDT_Int16, outputBounds=(extent[0], extent[2], extent[1], extent[3])) try: gdal.Warp(self.dem_output, dem_src, options=options) except Exception as e: LOGGER.fatal(e, exc_info=True) LOGGER.fatal('error using gdalwarp') else: return self.dem_output return None
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!")
def ogr_wkbwkt_test_import_bad_multipoint_wkb(): import struct wkb = struct.pack('B' * 30, 0, 0, 0, 0, 6, 0, 0, 0, 1, 0, 0, 0, 0, 1, 64, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0 ) gdal.PushErrorHandler('CPLQuietErrorHandler') old_val = gdal.GetConfigOption('CPL_DEBUG') gdal.SetConfigOption('CPL_DEBUG', 'ON') geom = ogr.CreateGeometryFromWkb(wkb) gdal.SetConfigOption('CPL_DEBUG', old_val) gdal.PopErrorHandler() if geom is not None: return 'fail' return 'success'
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("数据集创建完成!")