from osgeo import gdal,osr,ogr#定义投影sr = osr.SpatialReference('LOCAL_CS["arbitrary"]')#在内存中创建一个shape文件的图层,含有两个多边形source_ds = ogr.GetDriverByName('Memory').CreateDataSource( 'shapefile' )source_lyr = source_ds.CreateLayer('poly', srs=sr, geom_type=ogr.wkbPolygon )source_lyr.CreateField(ogr.FieldDefn('TCODE',ogr.OFTReal))wkt_geom = ['POLYGON((1020 1030 40,1020 1045 30,1050 1045 20,1050 1030 35,1020 1030 40))', 'POLYGON((1010 1046 85,1015 1055 35,1055 1060 26,1054 1048 35,1010 1046 85))']#栅格值celsius_field_values = [50,200]for i in range(len(wkt_geom)): feat = ogr.Feature(source_lyr.GetLayerDefn()) feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom[i])) feat.SetField('TCODE', celsius_field_values[i]) source_lyr.CreateFeature(feat)#在内存中,创建一个 100*100 大小的1波段的空白图像#‘’代表不往磁盘上写的话,文件名可以是空target_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 1, gdal.GDT_Byte )target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) )target_ds.SetProjection( sr.ExportToWkt())#调用栅格化函数。RasterizeLayer函数有四个参数,分别有栅格对象,波段,矢量对象,TCODE的属性值将为栅格值err = gdal.RasterizeLayer( target_ds, [1], source_lyr,options= ["ATTRIBUTE=TCODE"])#将内存中的图像,存储到硬盘文件上gdal.GetDriverByName('GTiff').CreateCopy('rasterized_poly.tif', target_ds)del target_dsdel source_ds
来源:https://www.cnblogs.com/ninicwang/p/11612397.html