def test_gdal_rasterize_lib_3(): import test_cli_utilities if test_cli_utilities.get_gdal_contour_path() is None: pytest.skip() gdaltest.runexternal(test_cli_utilities.get_gdal_contour_path() + ' ../gdrivers/data/n43.dt0 tmp/n43dt0.shp -i 10 -3d') with gdaltest.error_handler(): ds = gdal.Rasterize('/vsimem/bogus.tif', 'tmp/n43dt0.shp') assert ds is None, 'did not expected success' ds = gdal.Rasterize('', 'tmp/n43dt0.shp', format='MEM', outputType=gdal.GDT_Byte, useZ=True, layers=['n43dt0'], width=121, height=121, noData=0) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/n43dt0.shp') ds_ref = gdal.Open('../gdrivers/data/n43.dt0') assert ds.GetRasterBand(1).GetNoDataValue() == 0.0, \ 'did not get expected nodata value' assert ds.RasterXSize == 121 and ds.RasterYSize == 121, \ 'did not get expected dimensions' gt_ref = ds_ref.GetGeoTransform() gt = ds.GetGeoTransform() for i in range(6): assert abs(gt[i] - gt_ref[i]) <= 1e-6, 'did not get expected geotransform' wkt = ds.GetProjectionRef() assert wkt.find("WGS_1984") != -1, 'did not get expected SRS'
def test_gdal_rasterize_lib_102(): target_ds = gdal.GetDriverByName('MEM').Create('', 353, 226) target_ds.GetRasterBand(1).Fill(255) md = { 'HEIGHT_OFF': '430', 'HEIGHT_SCALE': '501', 'LAT_OFF': '-0.0734', 'LAT_SCALE': '0.2883', 'LINE_DEN_COEFF': '1 0.0002790015 0.001434672 1.481312e-07 5.866139e-06 1.878347e-07 -7.1677e-08 -1.099383e-05 1.968371e-06 -5.50509e-06 0 -1.227539e-08 0 0 2.40682e-07 -1.144941e-08 0 -1.884406e-08 0 0', 'LINE_NUM_COEFF': '0.002744972 -0.382552 -1.279674 -0.0001147828 0.001140472 1.262068e-07 -1.69402e-07 -0.005830625 -0.001964747 0 -2.006924e-07 3.066144e-07 3.005069e-06 2.103552e-06 -1.981401e-06 -1.636042e-06 7.045145e-06 -5.699422e-08 1.169591e-07 0', 'LINE_OFF': '112.98500331785', 'LINE_SCALE': '113.01499668215', 'LONG_OFF': '-4.498', 'LONG_SCALE': '0.5511', 'SAMP_DEN_COEFF': '1 0.001297913 0.0005878427 -0.0004554233 -7.353773e-05 7.928584e-06 -1.826261e-06 9.516839e-05 5.332457e-07 -4.236274e-05 -1.89316e-08 -1.520878e-06 -8.941367e-07 -7.770314e-07 1.413225e-06 9.681702e-08 -4.724849e-08 -2.244317e-07 1.0665e-08 4.212225e-08', 'SAMP_NUM_COEFF': '0.01819195 1.091934 -0.1976373 0.003166136 0.002648549 0.0003527143 -6.27017e-05 -0.01889831 -0.0005888535 1.729232e-07 3.037208e-06 0.000174218 -3.129558e-05 -4.602708e-05 2.724941e-05 -9.314161e-07 8.328574e-06 -1.240182e-05 -4.652876e-07 -1.322223e-07', 'SAMP_OFF': '176.619681301916', 'SAMP_SCALE': '177.068486184099' } target_ds.SetMetadata(md, "RPC") vector_ds = \ gdal.GetDriverByName('Memory').Create('', 0, 0, 0) sr = osr.SpatialReference() sr.ImportFromEPSG(4326) rast_lyr = vector_ds.CreateLayer('', srs=sr) # polygon with empty exterior ring geom = ogr.CreateGeometryFromWkt("""POLYGON ((-3.967081661665 0.0003251483162,-4.976841813513 0.0003251483162,-4.904140485134 0.2151010973779,-4.904124933286 0.2151433982916,-4.904107210626 0.2151848366149,-4.904087364764 0.2152253010321,-4.904065449011 0.2152646828438,-4.904041522241 0.2153028762585,-4.904015648726 0.2153397786774,-4.903987897971 0.2153752909697,-4.903958344523 0.2154093177387,-4.903927067771 0.2154417675784,-4.903894151734 0.2154725533188,-4.903859684834 0.2155015922603,-4.90382375966 0.2155288063955,-4.903786472717 0.2155541226193,-4.903747924169 0.2155774729247,-4.90370821757 0.2155987945858,-4.903667459582 0.2156180303263,-4.903625759694 0.2156351284732,-4.903583229924 0.2156500430959,-4.90353998452 0.2156627341291,-4.903496139651 0.2156731674811,-4.9034518131 0.2156813151247,-4.903407123938 0.2156871551729,-4.903362192216 0.2156906719376,-4.903317138633 0.2156918559717,-4.903272084216 0.2156907040946,-4.903227149995 0.2156872194006,-4.903182456677 0.2156814112505,-3.945022212098 0.0658193544758,-3.94497805444 0.0658112751384,-3.944934372574 0.0658009277184,-3.944891282916 0.0657883397923,-3.944848900303 0.0657735449078,-3.944807337687 0.0657565824944,-3.944766705836 0.0657374977579,-3.944727113036 0.0657163415606,-3.944688664805 0.0656931702851,-3.94465146361 0.0656680456844,-3.944615608594 0.0656410347174,-3.944581195314 0.0656122093701,-3.944548315483 0.065581646464,-3.944517056729 0.0655494274513,-3.944487502358 0.065515638198,-3.944459731134 0.0654803687547,-3.944433817071 0.0654437131168,-3.944409829229 0.0654057689742,-3.94438783154 0.0653666374506,-3.944367882627 0.0653264228341,-3.944350035657 0.0652852322995,-3.944334338192 0.0652431756223,-3.944320832068 0.0652003648864,-3.944309553279 0.0651569141855,-3.944300531884 0.0651129393185,-3.944293791926 0.0650685574815,-3.944289351367 0.0650238869551,-3.944287222041 0.0649790467894,-3.944287409623 0.0649341564864,-3.944289913614 0.0648893356818,-3.94429472734 0.0648447038262,-3.944301837972 0.0648003798665,-3.94431122656 0.064756481929,-3.944322868082 0.0647131270048,-3.944336731513 0.0646704306378,-3.967081661665 0.0003251483162))""") feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(geom) rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[0]) assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() assert checksum == 1604, 'Did not get expected image checksum' # Re-try with transformer options target_ds.GetRasterBand(1).Fill(255) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[0], transformerOptions=['RPC_HEIGHT=1000']) assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() assert checksum == 2003, 'Did not get expected image checksum' target_ds = None
def test_gdal_rasterize_lib_3(): import test_cli_utilities if test_cli_utilities.get_gdal_contour_path() is None: return 'skip' gdaltest.runexternal(test_cli_utilities.get_gdal_contour_path() + ' ../gdrivers/data/n43.dt0 tmp/n43dt0.shp -i 10 -3d') with gdaltest.error_handler(): ds = gdal.Rasterize('/vsimem/bogus.tif', 'tmp/n43dt0.shp') if ds is not None: gdaltest.post_reason('did not expected success') return 'fail' ds = gdal.Rasterize('', 'tmp/n43dt0.shp', format='MEM', outputType=gdal.GDT_Byte, useZ=True, layers=['n43dt0'], width=121, height=121, noData=0) ogr.GetDriverByName('ESRI Shapefile').DeleteDataSource('tmp/n43dt0.shp') ds_ref = gdal.Open('../gdrivers/data/n43.dt0') if ds.GetRasterBand(1).GetNoDataValue() != 0.0: gdaltest.post_reason('did not get expected nodata value') return 'fail' if ds.RasterXSize != 121 or ds.RasterYSize != 121: gdaltest.post_reason('did not get expected dimensions') return 'fail' gt_ref = ds_ref.GetGeoTransform() gt = ds.GetGeoTransform() for i in range(6): if (abs(gt[i] - gt_ref[i]) > 1e-6): gdaltest.post_reason('did not get expected geotransform') print(gt) print(gt_ref) return 'fail' wkt = ds.GetProjectionRef() if wkt.find("WGS_1984") == -1: gdaltest.post_reason('did not get expected SRS') print(wkt) return 'fail' return 'success'
def test_gdal_rasterize_lib_100(): target_ds = gdal.GetDriverByName('MEM').Create('', 100, 100) # Create a layer to rasterize from. vector_ds = \ gdal.GetDriverByName('Memory').Create('', 0, 0, 0) rast_lyr = vector_ds.CreateLayer('rast1') wkt_geom = 'POLYGON((20 20,20 80,80 80,80 20,20 20))' feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom)) rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[255]) if ret != 1: gdaltest.post_reason('fail') return 'fail' # Check results. expected = 44190 checksum = target_ds.GetRasterBand(1).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason('Did not get expected image checksum') return 'fail' target_ds = None return 'success'
def test_gdal_rasterize_lib_100(): target_ds = gdal.GetDriverByName('MEM').Create('', 100, 100) # Create a layer to rasterize from. vector_ds = \ gdal.GetDriverByName('Memory').Create('', 0, 0, 0) rast_lyr = vector_ds.CreateLayer('rast1') wkt_geom = 'POLYGON((20 20,20 80,80 80,80 20,20 20))' feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom)) rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[255]) assert ret == 1 # Check results. expected = 44190 checksum = target_ds.GetRasterBand(1).Checksum() assert checksum == expected, 'Did not get expected image checksum' target_ds = None
def test_gdal_rasterize_lib_4(): # Setup working spatial reference # sr_wkt = 'LOCAL_CS["arbitrary"]' # sr = osr.SpatialReference( sr_wkt ) sr = osr.SpatialReference() sr.ImportFromEPSG(32631) sr_wkt = sr.ExportToWkt() # Create a raster to rasterize into. for optim in ['RASTER', 'VECTOR', 'AUTO']: target_ds = gdal.GetDriverByName('MEM').Create('', 100, 100, 3, gdal.GDT_Byte) target_ds.SetGeoTransform((1000, 1, 0, 1100, 0, -1)) target_ds.SetProjection(sr_wkt) # Create a layer to rasterize from. vector_ds = \ gdal.GetDriverByName('Memory').Create('', 0, 0, 0) rast_lyr = vector_ds.CreateLayer('rast1', srs=sr) rast_lyr.GetLayerDefn() field_defn = ogr.FieldDefn('foo') rast_lyr.CreateField(field_defn) # Add a polygon. wkt_geom = 'POLYGON((1020 1030,1020 1045,1050 1045,1050 1030,1020 1030))' feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom)) rast_lyr.CreateFeature(feat) # Add feature without geometry to test fix for #3310 feat = ogr.Feature(rast_lyr.GetLayerDefn()) rast_lyr.CreateFeature(feat) # Add a linestring. wkt_geom = 'LINESTRING(1000 1000, 1100 1050)' feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom)) rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, bands=[3, 2, 1], burnValues=[200, 220, 240], layers='rast1', optim=optim) assert ret == 1 # Check results. expected = 6452 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum, optim) pytest.fail('Did not get expected image checksum') target_ds = None
def test_gdal_rasterize_lib_101(): target_ds = gdal.GetDriverByName('MEM').Create('', 100, 100) # Create a layer to rasterize from. vector_ds = \ gdal.GetDriverByName('Memory').Create('', 0, 0, 0) rast_lyr = vector_ds.CreateLayer('rast1') # polygon with empty exterior ring geom = ogr.CreateGeometryFromJson( '{ "type": "Polygon", "coordinates": [ [ ] ] }') feat = ogr.Feature(rast_lyr.GetLayerDefn()) feat.SetGeometryDirectly(geom) rast_lyr.CreateFeature(feat) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[255]) assert ret == 1 # Check results. checksum = target_ds.GetRasterBand(1).Checksum() assert checksum == 0, 'Did not get expected image checksum' target_ds = None
def gdalMask(rasterpath): vector_layer = "/Data/area.shp" raster_layer = rasterpath target_layer = rasterpath + "mask.tif" # open the raster layer and get its relevant properties raster_ds = gdal.Open(raster_layer, gdal.GA_ReadOnly) xSize = raster_ds.RasterXSize ySize = raster_ds.RasterYSize geotransform = raster_ds.GetGeoTransform() projection = raster_ds.GetProjection() # create the target layer (1 band) driver = gdal.GetDriverByName('GTiff') target_ds = driver.Create(target_layer, xSize, ySize, bands=1, eType=gdal.GDT_Byte, options=["COMPRESS=DEFLATE"]) target_ds.SetGeoTransform(geotransform) target_ds.SetProjection(projection) # rasterize the vector layer into the target one ds = gdal.Rasterize(target_ds, vector_layer) target_ds = None return target_layer
def burn_vector_mask_into_raster(raster_path, vector_path, out_path, vector_field=None): """Create a new raster based on the input raster with vector features burned into the raster. To be used as a mask for pixels in the vector. Parameters ---------- raster_path : str vector_path : str out_path : str Path for output raster. Format and Datatype are the same as ``ras``. vector_field : str or None Name of a field in the vector to burn values from. If None, all vector features are burned with a constant value of 1. Returns ------- gdal.Dataset Single band raster with vector geometries burned. """ ras = open_raster(raster_path) vec = open_vector(vector_path) # Check EPSG are same, if not reproject vector. if not same_epsg(ras, vec): raise ValueError( 'Raster and vector are not the same EPSG.\n' '{} != {}'.format(get_epsg(ras), get_epsg(vec)) ) # Create an empty for GDALRasterize to burn vector values to. out_ds = _create_empty_raster(ras, out_path, n_bands=1, no_data_value=0) if vector_field is None: # Use a constant value for all features. burn_values = [1] attribute = None else: # Use the values given in the vector field. burn_values = None attribute = vector_field # Options for Rasterize. # note: burnValues and attribute are exclusive. rasterize_opts = gdal.RasterizeOptions( bands=[1], burnValues=burn_values, attribute=attribute, allTouched=True) _ = gdal.Rasterize(out_ds, vector_path, options=rasterize_opts) # Explicitly close raster to ensure it is saved. out_ds.FlushCache() out_ds = None return open_raster(out_path)
def test_gdal_rasterize_lib_multipolygon(): sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference(sr_wkt) # Try rasterizing a multipolygon vector_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) layer = vector_ds.CreateLayer('', sr) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly( ogr.CreateGeometryFromWkt( 'MULTIPOLYGON (((0 0,0 1,1 1,0 0)),((1 1,2 1,2 0,1 1)))')) layer.CreateFeature(feature) target_ds = gdal.GetDriverByName('MEM').Create('', 3, 2) target_ds.SetGeoTransform((-0.5, 1, 0, 1.5, 0, -1)) target_ds.SetSpatialRef(sr) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[10]) assert ret == 1 cs1 = target_ds.GetRasterBand(1).Checksum() # And now each of its parts vector_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) layer = vector_ds.CreateLayer('', sr) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly( ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,0 0))')) layer.CreateFeature(feature) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly( ogr.CreateGeometryFromWkt('POLYGON ((1 1,2 1,2 0,1 1))')) layer.CreateFeature(feature) target_ds = gdal.GetDriverByName('MEM').Create('', 3, 2) target_ds.SetGeoTransform((-0.5, 1, 0, 1.5, 0, -1)) target_ds.SetSpatialRef(sr) ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[10]) assert ret == 1 cs2 = target_ds.GetRasterBand(1).Checksum() # Check that results are the same assert cs1 == cs2
def shape_rasterize(shp_path, out_path, tif_path): """ 统计矢量转换为栅格 :param shp_path: 转换矢量 :param out_path: 输出路径 若设置为空字符串则默认以MEM模式输出 :param tif_path: 为转栅格提供xy向分辨率 :return: """ tif_obj = GeoTiffFile(tif_path) tif_obj.readTif() x_res = tif_obj.getXRes() y_res = tif_obj.getYRes() shp_obj = ShapeFile(shp_path) shp_obj.readShp() shp_extend = shp_obj.getExtent() out_bounds = (shp_extend["xMin"], shp_extend["yMin"], shp_extend["xMax"], shp_extend["yMax"]) if out_path == '': options = gdal.RasterizeOptions(outputBounds=out_bounds, outputType=gdal.GDT_UInt16, noData=65535, attribute="obj_id", useZ=False, xRes=x_res, yRes=y_res, format="MEM") ds = gdal.Rasterize(out_path, shp_path, options=options) else: options = gdal.RasterizeOptions(outputBounds=out_bounds, outputType=gdal.GDT_UInt16, noData=65535, attribute="obj_id", useZ=False, xRes=x_res, yRes=y_res, format="GTiff") ds = gdal.Rasterize(out_path, shp_path, options=options) return ds
def PolygonToRaster(in_path, out_path, x_res, y_res, field_name, out_bounds=None, no_data=65535): """ 面矢量转为栅格 :param in_path: str 输入矢量文件路径 :param out_path: str 输出栅格文件路径 :param x_res: float 输出栅格x向分辨率 :param y_res: float 输出栅格y向分辨率 :param field_name: str 栅格赋值的矢量字段名 :param out_bounds: tuple 输出栅格范围 [xmin, ymin, xmax, ymax] :param no_data: int 无效值大小 :return: """ try: if not out_bounds: gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO") # 为了支持中文路径,请添加 gdal.SetConfigOption("SHAPE_ENCODING", "GBK") # 为了使属性表字段支持中文,请添加 ogr.RegisterAll() # 注册所有的驱动 layer = ogr.Open(in_path, gdal.GA_ReadOnly).GetLayer(0) shp_extent = layer.GetExtent() out_bounds = (shp_extent[0], shp_extent[2], shp_extent[1], shp_extent[3]) options = gdal.RasterizeOptions(outputBounds=out_bounds, outputType=gdal.GDT_UInt16, noData=no_data, attribute=field_name, useZ=False, xRes=x_res, yRes=y_res, format="GTiff") ds = gdal.Rasterize(out_path, in_path, options=options) if not ds: return False del ds return True except Exception as e: print(e) return False
def rasterize(in_lyr_path, out_raster_path, template_path): """Rasterizing an input Args: in_lyr_path ([type]): [description] out_raster_ ([type]): [description] template_path ([type]): [description] """ log = Logger('VBETRasterize') ds_path, lyr_path = VectorBase.path_sorter(in_lyr_path) progbar = ProgressBar(100, 50, "Rasterizing ") with rasterio.open(template_path) as raster: t = raster.transform raster_bounds = raster.bounds def poly_progress(progress, _msg, _data): progbar.update(int(progress * 100)) # Rasterize the features (roads, rail etc) and calculate a raster of Euclidean distance from these features progbar.update(0) # Rasterize the polygon to a temporary file with TempRaster('vbet_rasterize') as tempfile: log.debug('Temporary file: {}'.format(tempfile.filepath)) gdal.Rasterize( tempfile.filepath, ds_path, layers=[lyr_path], xRes=t[0], yRes=t[4], burnValues=1, outputType=gdal.GDT_Int16, creationOptions=['COMPRESS=LZW'], # outputBounds --- assigned output bounds: [minx, miny, maxx, maxy] outputBounds=[ raster_bounds.left, raster_bounds.bottom, raster_bounds.right, raster_bounds.top ], callback=poly_progress) progbar.finish() # Now mask the output correctly mask_rasters_nodata(tempfile.filepath, template_path, out_raster_path)
def processAlgorithm(self, parameters, context, feedback): self.feedback = feedback # Needed for callback function geojson = json.loads( self.parameterAsString(parameters, 'INPUT', context)) model_file = self.parameterAsFile(parameters, 'MODEL_FILE', context) out_file = self.parameterAsFile(parameters, 'OUTPUT', context) json_file = GetTempFilename('.geojson') with open(json_file, 'w') as f: json.dump(geojson, f, separators=(',', ': ')) gdal.UseExceptions() # Assumes an image with no rotation gt = gdal.Info(model_file, format='json')['geoTransform'] x_size, y_size = gdal.Info(model_file, format='json')['size'] x_min = min(gt[0], gt[0] + x_size * gt[1]) x_max = max(gt[0], gt[0] + x_size * gt[1]) y_min = min(gt[3], gt[3] + y_size * gt[5]) y_max = max(gt[3], gt[3] + y_size * gt[5]) output_bounds = [x_min, y_min, x_max, y_max] x_res = gt[1] y_res = gt[5] res = gdal.Rasterize( out_file, json_file, format='GTiff', outputBounds=output_bounds, initValues=-32767, # Areas that are masked out burnValues=1, # Areas that are NOT masked out xRes=x_res, yRes=y_res, outputSRS="epsg:4326", outputType=gdal.GDT_Int16, creationOptions=['COMPRESS=LZW'], callback=self.progress_callback) os.remove(json_file) if not res or self.feedback.isCanceled(): return {'SUCCESS': False} else: return {'SUCCESS': True}
def work(self): self.toggle_show_progress.emit(True) self.toggle_show_cancel.emit(True) json_file = tempfile.NamedTemporaryFile(suffix='.geojson').name with open(json_file, 'w') as f: json.dump(self.geojson, f, separators=(',', ': ')) f.close() gdal.UseExceptions() if self.model_file: # Assumes an image with no rotation gt = gdal.Info(self.model_file, format='json')['geoTransform'] x_size, y_size = gdal.Info(self.model_file, format='json')['size'] x_min = min(gt[0], gt[0] + x_size * gt[1]) x_max = max(gt[0], gt[0] + x_size * gt[1]) y_min = min(gt[3], gt[3] + y_size * gt[5]) y_max = max(gt[3], gt[3] + y_size * gt[5]) output_bounds = [x_min, y_min, x_max, y_max] x_res = gt[1] y_res = gt[5] else: output_bounds = None x_res = None y_res = None res = gdal.Rasterize( self.out_file, json_file, format='GTiff', outputBounds=output_bounds, initValues=-32767, # Areas that are masked out burnValues=1, # Areas that are NOT masked out xRes=x_res, yRes=y_res, outputSRS="epsg:4326", outputType=gdal.GDT_Int16, creationOptions=['COMPRESS=LZW'], callback=self.progress_callback) if res: return True else: return None
def shp_rasterize(in_path, out_path, xres, yres, field_name, out_bounds=None, nodataValue=65535): """ 矢量文件栅格化 :param in_path: str: 输入矢量文件路径 :param out_path: str: 输出栅格文件路径 :param xres: float: x向分辨率 :param yres: float: y向分辨率 :param field_name: str: 栅格化字段 :return: """ try: shp_obj = ShapeFile(in_path) shp_obj.readShp() if not out_bounds: shp_extend = shp_obj.getExtent() out_bounds = (shp_extend["xMin"], shp_extend["yMin"], shp_extend["xMax"], shp_extend["yMax"]) # outputBounds [xmin, ymin, xmax, ymax] options = gdal.RasterizeOptions(outputBounds=out_bounds, outputType=gdal.GDT_UInt16, noData=nodataValue, attribute=field_name, useZ=False, xRes=xres, yRes=yres, format="GTiff") ds = gdal.Rasterize(out_path, in_path, options=options) if not ds: return False del ds return True except Exception as e: print(e) return False
def rasterize(shp, resolution, output_dest): """Convert vector to raster.""" input_shp = ogr.Open(shp) shp_layer = input_shp.GetLayer() pixel_size = resolution xmin, xmax, ymin, ymax = shp_layer.GetExtent() head, tail = os.path.split(shp) output_raster = output_dest + tail[:-4] + '.tif' print(output_raster) ds = gdal.Rasterize(output_raster, shp, xRes=pixel_size, yRes=pixel_size, burnValues=255, outputBounds=[xmin, ymin, xmax, ymax], outputType=gdal.GDT_Byte) ds = None return output_raster
def gdal_rasterize(src, dst, options): """ a simple wrapper for :osgeo:func:`gdal.Rasterize` Parameters ---------- src: str or :osgeo:class:`ogr.DataSource` the input data set dst: str the output data set options: dict additional parameters passed to :osgeo:func:`gdal.Rasterize`; see :osgeo:func:`gdal.RasterizeOptions` Returns ------- """ out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options)) out = None
def test_gdal_rasterize_lib_inverse(): sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference(sr_wkt) # Try rasterizing a multipolygon vector_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) layer = vector_ds.CreateLayer('', sr) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly(ogr.CreateGeometryFromWkt('MULTIPOLYGON (((1 1,1 9,4 9,4 1,1 1),(2 2,2 8,3 8,3 2,2 2)))')) layer.CreateFeature(feature) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POLYGON ((5 1,5 9,9 9,9 1,5 1))')) layer.CreateFeature(feature) # Will not be rasterized feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly(ogr.CreateGeometryFromWkt('POINT (5 5)')) layer.CreateFeature(feature) target_ds = gdal.GetDriverByName('MEM').Create('', 11, 11) target_ds.SetGeoTransform((-0.5, 1, 0, 10.5, 0, -1)) target_ds.SetSpatialRef(sr) with gdaltest.error_handler(): ret = gdal.Rasterize(target_ds, vector_ds, burnValues=[9], inverse=True) assert ret == 1 expected = (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 0, 9, 0, 9, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,) assert struct.unpack('B'* 121, target_ds.ReadRaster()) == expected
def rasterize_feat_shp_ds(shp_ds, layer_name, feat_name, feat_id, raster_ds, all_touched=False, exclude=False): if not exclude: str_eq = "='" else: str_eq = "!='" sql_stat = 'SELECT * FROM ' + layer_name + ' WHERE ' + feat_name + str_eq + feat_id + "'" opts = gdal.RasterizeOptions(burnValues=[1], bands=[1], SQLStatement=sql_stat, allTouched=all_touched) gdal.Rasterize(raster_ds, shp_ds, options=opts)
def gdal_rasterize(src, dst, options): """ a simple wrapper for gdal.Rasterize Parameters ---------- src: str or ogr.DataSource the input data set dst: str the output data set options: dict additional parameters passed to gdal.Rasterize; see http://gdal.org/python/osgeo.gdal-module.html#RasterizeOptions Returns ------- """ out = gdal.Rasterize(dst, src, options=gdal.RasterizeOptions(**options)) out = None
def rasterize_shp(fn_shp, fn_raster_ref, all_touched=False): #create memory raster based on reference raster raster_ds = create_mem_raster_on_ref(fn_raster_ref) #open .shp with GDAL shp_ds = gdal.OpenEx(fn_shp, gdal.OF_VECTOR) #rasterize opts = gdal.RasterizeOptions(burnValues=[1], bands=[1], allTouched=all_touched) gdal.Rasterize(raster_ds, shp_ds, options=opts) #get rasterized array rast_array = raster_ds.GetRasterBand(1).ReadAsArray() rast_array = rast_array.astype(float) rast_array[rast_array != 1] = np.nan #close shp shp_ds = None raster_ds = None return ~np.isnan(rast_array)
def hand_rasterize(in_lyr_path: str, template_dem_path: str, out_raster_path: str): log = Logger('hand_rasterize') ds_path, lyr_path = VectorBase.path_sorter(in_lyr_path) g = gdal.Open(template_dem_path) geo_t = g.GetGeoTransform() width, height = g.RasterXSize, g.RasterYSize xmin = min(geo_t[0], geo_t[0] + width * geo_t[1]) xmax = max(geo_t[0], geo_t[0] + width * geo_t[1]) ymin = min(geo_t[3], geo_t[3] + geo_t[-1] * height) ymax = max(geo_t[3], geo_t[3] + geo_t[-1] * height) # Close our dataset g = None progbar = ProgressBar(100, 50, "Rasterizing for HAND") def poly_progress(progress, _msg, _data): progbar.update(int(progress * 100)) # https://gdal.org/programs/gdal_rasterize.html # https://gdal.org/python/osgeo.gdal-module.html#RasterizeOptions gdal.Rasterize( out_raster_path, ds_path, layers=[lyr_path], height=height, width=width, burnValues=1, outputType=gdal.GDT_CFloat32, creationOptions=['COMPRESS=LZW'], # outputBounds --- assigned output bounds: [minx, miny, maxx, maxy] outputBounds=[xmin, ymin, xmax, ymax], callback=poly_progress) progbar.finish() # Rasterize the features (roads, rail etc) and calculate a raster of Euclidean distance from these features progbar.update(0)
def test_gdal_rasterize_lib_int64_attribute(): # Try rasterizing a multipolygon vector_ds = gdal.GetDriverByName('Memory').Create('', 0, 0, 0) layer = vector_ds.CreateLayer('') layer.CreateField(ogr.FieldDefn('val', ogr.OFTInteger64)) feature = ogr.Feature(layer.GetLayerDefn()) feature.SetGeometryDirectly( ogr.CreateGeometryFromWkt('POLYGON ((0 0,0 1,1 1,1 0,0 0))')) val = (1 << 63) - 1 # not exactly representable as a double feature['val'] = val layer.CreateFeature(feature) target_ds = gdal.Rasterize('', vector_ds, format='MEM', attribute='val', width=2, height=2) assert target_ds is not None assert target_ds.GetRasterBand(1).DataType == gdal.GDT_Int64 assert struct.unpack('Q' * 4, target_ds.ReadRaster())[0] == val
def main(in_file, shp_file, nodata, out_file): # 新建缓存文件夹 sys_str = platform.system() if (sys_str == 'Windows'): temp_dir = os.path.join(tempfile.gettempdir(), 'gdal_mask2') if os.path.exists(temp_dir): shutil.rmtree(temp_dir) os.mkdir(temp_dir) else: rand_str = ''.join( random.sample(string.ascii_letters + string.digits, 4)) temp_dir = os.path.join(r'/data6', 'gdal_%s' % rand_str) if not os.path.exists(temp_dir): os.mkdir(temp_dir) # 打开影像 source_dataset = gdal.Open(in_file) if source_dataset is None: sys.exit('Problem opening file %s !' % in_file) # 获取数据基本信息 xsize = source_dataset.RasterXSize ysize = source_dataset.RasterYSize num_band = source_dataset.RasterCount data_type = source_dataset.GetRasterBand(1).DataType in_geo = source_dataset.GetGeoTransform() source_proj = source_dataset.GetProjectionRef() mask_file = os.path.join( temp_dir, '%s_mask.tif' % (os.path.splitext(os.path.basename(shp_file))[0])) out_driver = gdal.GetDriverByName('GTiff') if os.path.exists(mask_file): out_driver.Delete(mask_file) print('shape to mask raster start...') gdal.Rasterize(mask_file, shp_file, burnValues=1, xRes=abs(in_geo[1] / 2), yRes=abs(in_geo[5] / 2), outputType=data_type, callback=progress) print('shape to mask raster done.') print('mask raster start...') mask_sds = gdal.Open(mask_file) if mask_sds is None: sys.exit('Problem opening file %s !' % mask_file) separate_files = [] for iband in range(num_band): single_file = os.path.join( temp_dir, '%s_band%d.tif' % (os.path.splitext(os.path.basename(in_file))[0], iband + 1)) single_sds = out_driver.Create(single_file, xsize, ysize, 1, data_type) single_sds.GetRasterBand(1).WriteArray( source_dataset.GetRasterBand(1 + iband).ReadAsArray(), 0, 0) single_sds.SetGeoTransform(in_geo) single_sds.SetProjection(source_proj) single_sds = None # gdal.Translate(single_file, in_file, bandList=[iband+1]) separate_files.append(single_file) progress((1 + iband) / num_band * 0.5) separate_files.append(mask_file) vrt_file = os.path.join( temp_dir, '%s_vrt.vrt' % (os.path.splitext(os.path.basename(in_file))[0])) gdal.BuildVRT(vrt_file, separate_files, resolution='user', xRes=abs(in_geo[1]), yRes=abs(in_geo[5]), separate=True, options=['-r', 'near']) vrt_sds = gdal.Open(vrt_file) if vrt_sds is None: sys.exit('Problem opening file %s !' % vrt_file) out_geotransform = vrt_sds.GetGeoTransform() out_projection = vrt_sds.GetProjectionRef() out_xsize = vrt_sds.RasterXSize out_ysize = vrt_sds.RasterYSize out_sds = out_driver.Create(out_file, out_xsize, out_ysize, num_band, data_type) num_xblock = 10000 for xoffset in range(0, out_xsize, num_xblock): if xoffset + num_xblock < out_xsize: num_xsize = num_xblock else: num_xsize = out_xsize - xoffset block_data = vrt_sds.ReadAsArray(xoffset, 0, num_xsize, ysize) ind = np.where(block_data[num_band, :, :] == 0) for iband in range(num_band): block_data[iband, :, :][ind] = nodata out_sds.GetRasterBand(iband + 1).WriteArray( block_data[iband, :, :], xoffset, 0) block_data = None ind = None # ind = np.where(out_sds.ReadAsArray()[num_band, :, :].reshape(out_ysize, out_xsize) == 0) # # for iband in range(num_band): # band_data = out_sds.ReadAsArray()[iband, :, :].reshape(out_ysize, out_xsize) # band_data[ind] = nodata # out_sds.GetRasterBand(iband + 1).WriteArray(band_data, 0, 0) # band_data = None # progress((xoffset + num_xsize + 1) / out_xsize + 0.5) # out_sds.SetGeoTransform(out_geotransform) out_sds.SetProjection(out_projection) data = None mask_data = None vrt_sds = None out_sds = None source_dataset = None mask_sds = None print('mask raster done.') shutil.rmtree(temp_dir) print() print('all done')
def process_rain(adate,TC_Rain): """process rainfall data""" ## VRT template to read the csv vrt_template="""<OGRVRTDataSource> <OGRVRTLayer name='{}'> <SrcDataSource>{}</SrcDataSource> <GeometryType>wkbPoint</GeometryType> <GeometryField encoding="PointFromColumns" x="lon" y="lat" z="Z"/> </OGRVRTLayer> </OGRVRTDataSource>""" ## Read each text file and create the separate tiff file for i in TC_Rain: with open(i,'r') as f: variable=csv.reader(f, delimiter=' ') row_count=1 for row in variable: if row_count == 1: while ('' in row): row.remove('') XLC=float(row[0]) XRC=float(row[1]) YBC=float(row[2]) YTC=float(row[3]) res=float(row[4]) nrows=float(row[5]) ncol=float(row[6]) row_count = row_count + 1 df = (pd.read_table(i, skiprows=1, delim_whitespace=True, names=('lat', 'lon', 'Z'))).fillna(-999) df.sort_values(by=["lat","lon"], ascending=[False, True]) df=df[['lon','lat','Z']] df = df[df.lon >= XLC] df = df[df.lon <= XRC] df = df[df.lat >= YBC] df = df[df.lat <= YTC] df = df[df.Z > 0] df.to_csv(i.replace(".ascii",".csv"),index=False, sep=" ") with open(i.replace(".ascii",".vrt"),"w") as g: g.write(vrt_template.format(i.replace(".ascii",""),i.replace(".ascii",".csv"))) g.close() r=gdal.Rasterize(i.replace(".ascii",".tiff"),i.replace(".ascii",".vrt"),outputSRS="EPSG:4326",xRes=res, yRes=res,attribute="Z", noData=-999) r=None os.remove(i.replace(".ascii",".csv")) ##merge all tiffs file als # nd delete the individual tiff, vrt and ascii file TC_Rain_tiff=[] for i in TC_Rain: TC_Rain_tiff.append(i.replace(".ascii",".tiff")) filename="hwrf."+ adate +"rainfall.vrt" raintiff = filename.replace(".vrt",".tiff") vrt = gdal.BuildVRT(filename, TC_Rain_tiff) gdal.Translate(raintiff, vrt) vrt=None # no need #gdalcmd = "gdal_translate -of GTiff " + filename + " " + raintiff #subprocess.call(gdalcmd, shell=True) # create a zipfile zip_file="hwrf."+ adate +"rainfall.zip" with zipfile.ZipFile(zip_file, 'w',zipfile.ZIP_DEFLATED) as zipObj: for i in TC_Rain_tiff: asfile = i.replace(".tiff",".ascii") zipObj.write(asfile) for i in TC_Rain_tiff: os.remove(i) os.remove(i.replace(".tiff",".ascii")) os.remove(i.replace(".tiff",".vrt")) return raintiff
def cellneigh_ctry(raster=None, region=None, vector=None, csize=10, rank=1): """ Compute number of spatial cells and neighbours. :param raster: Path to raster file to compute region. :param vector: Path to vector file with country borders. :param region: List/tuple of region coordinates (east, west, south, north). :param csize: Spatial cell size (in km). :param rank: Rank of the neighborhood (1 for chess king's move). :return: List of length 2 with number of neighbours for each cell \ and adjacent cells. """ # Region if raster is not None: r = gdal.Open(raster) ncol_r = r.RasterXSize nrow_r = r.RasterYSize gt = r.GetGeoTransform() Xmin = gt[0] Xmax = gt[0] + gt[1] * ncol_r Ymin = gt[3] + gt[5] * nrow_r Ymax = gt[3] elif region is not None: Xmin = region[0] Xmax = region[1] Ymin = region[2] Ymax = region[3] else: print("raster or region must be specified") sys.exit(1) # Cell number from region print("Compute number of {} x {} km spatial cells".format(csize, csize)) csize = csize * 1000 # Transform km in m ncol = np.int(np.ceil((Xmax - Xmin) / csize)) nrow = np.int(np.ceil((Ymax - Ymin) / csize)) Xmax_new = Xmin + ncol * csize Ymin_new = Ymax + nrow * (-csize) ncell = ncol * nrow print("... {} cells ({} x {})".format(ncell, nrow, ncol)) # Cells within country borders (rasterizing method) cb_ds = gdal.OpenEx(vector, gdal.OF_VECTOR) rOptions = gdal.RasterizeOptions( xRes=csize, yRes=-csize, allTouched=True, outputBounds=[Xmin, Ymin_new, Xmax_new, Ymax], burnValues=1, noData=0) outfile = "/vsimem/tmpfile" ds = gdal.Rasterize(outfile, cb_ds, options=rOptions) mask = ds.ReadAsArray() ds = None gdal.Unlink(outfile) y_in, x_in = np.where(mask == 1) cell_in = y_in * ncol + x_in # Adjacent cells and number of neighbors print("Identify adjacent cells and compute number of neighbors") nneigh = [] adj = [] adj_sort = [] around = np.arange(-rank, rank + 1) for i in range(nrow): for j in range(ncol): if mask[i, j] == 1: I = i + around Iprim = I[(I >= 0) & (I < nrow)] J = j + around Jprim = J[(J >= 0) & (J < ncol)] # Loop on potential neighbors nneighbors = 0 for cy in Iprim: for cx in Jprim: if (not (cy == i and cx == j)) and (mask[cy, cx] == 1): adj.append(cy * ncol + cx) nneighbors += 1 nneigh.append(nneighbors) nneigh = np.array(nneigh) adj = np.array(adj) for i in adj: adj_sort.append(np.flatnonzero(cell_in == i)[0]) adj_sort = np.array(adj_sort) return (nneigh, adj_sort, cell_in, ncell)
if not os.path.exists(output_folder): os.makedirs(output_folder) match_fn = f"data/nc/MODIS/MCD64A1/{region.get('name')}/MCD64A1_500m.nc" match_ds = xarray.open_dataset(match_fn) stack = [] for feature in ACCESSIBILITY_FEATURES: # Create temporal raster rasterize_options = gdal.RasterizeOptions( xRes=xres, yRes=yres, allTouched=True, burnValues=[1] ) temp1 = gdal.Rasterize( "/vsimem/temp", feature.get("path"), options=rasterize_options ) temp1_band = temp1.GetRasterBand(1) # Create temporal proximity raster driver = gdal.GetDriverByName("MEM") temp2 = driver.Create("temp2", temp1.RasterXSize, temp1.RasterYSize) temp2.SetGeoTransform(temp1.GetGeoTransform()) temp2.SetProjection(temp1.GetProjection()) temp2_band = temp2.GetRasterBand(1) gdal.ComputeProximity(temp1_band, temp2_band, ["VALUES=1"]) temp2_band.FlushCache() # Clip to region area warp_options = gdal.WarpOptions( outputBounds=match_ds.rio.bounds(),
def predict_and_save(self, datas, fn): geo = self.geo prj = self.prj xsize = self.xsize ysize = self.ysize obsdate = self.obsdate obswkt = self.obswkt username = self.username password = self.password translations = self.translations resolutions = self.resolutions todate = obsdate + timedelta(days=14) fromdate = obsdate - timedelta(days=14) ptsfn = get_hotspots(obswkt, fromdate=fromdate, todate=todate, t_prj=prj, username=username, password=password) fd = ogr.Open(ptsfn) layer = fd.GetLayer() sensors = set() for ftr in layer: sensors.add(ftr.GetField('sensor')) driver = ogr.GetDriverByName('GeoJSON') tsr = osr.SpatialReference() tsr.ImportFromProj4(prj) datas = [] for sensor in sensors: layer.SetAttributeFilter(f"sensor='{sensor}'") count = layer.GetFeatureCount() ds = driver.CreateDataSource(f"/vsimem/{sensor}.json") olayer = ds.CreateLayer(sensor, tsr, geom_type=ogr.wkbMultiPolygon) ldef = layer.GetLayerDefn() for i in range(ldef.GetFieldCount()): fdef = ldef.GetFieldDefn(i) olayer.CreateField(fdef) oldef = olayer.GetLayerDefn() for ftr in layer: geom = ftr.GetGeometryRef() dx, dy = translations[sensor] if dx != 0 or dy != 0: x, y = geom.GetPoint_2D() geom.SetPoint(0, x + dx, y + dy) geom = geom.Buffer(resolutions[sensor]) oftr = ogr.Feature(oldef) oftr.SetGeometry(geom) for i in range(oldef.GetFieldCount()): oftr.SetField( oldef.GetFieldDefn(i).GetNameRef(), ftr.GetField(i)) olayer.CreateFeature(oftr) olayer.SyncToDisk() ds = None geo = self.geo bounds = [ geo[0], geo[3], geo[0] + xsize * geo[1], geo[3] + geo[5] * ysize ] ds = gdal.Rasterize(f"{sensor}.tif", f"/vsimem/{sensor}.json", outputBounds=bounds, width=xsize, height=ysize, attribute="temp_kelvin") geo = ds.GetGeoTransform() prj = ds.GetProjection() data = ds.ReadAsArray() #pl, pu = np.percentile(data, PROBPERCCLIP) #if np.abs(pu - pl) > 0: # data -= pl # data /= (pu - pl) # np.clip(data, 0, 1, out=data) #log(f"{sensor}\tpoints: {count} pl: {pl} pu: {pu}") #data /= 100. #data = morphology.convex_hull_object(data > 0, connectivity=2) filters.gaussian(data, sigma=25, preserve_range=True, truncate=3, output=data) mask = data > 0 morphology.binary_erosion(mask, morphology.disk(10), out=mask) data[mask == 0] = np.nan rb = ds.GetRasterBand(1) rb.WriteArray(data) rb.SetNoDataValue(np.nan) datas.append(data) data = np.dstack(datas) #data = np.nanmean(data, axis=-1) #data = data[:,:,np.newaxis] #sensors = ['squashed'] driver = gdal.GetDriverByName("GTiff") ds = driver.Create(fn, data.shape[1], data.shape[0], data.shape[2], gdal.GDT_Float32) ds.SetGeoTransform(geo) ds.SetProjection(prj) for i, sensor in zip(range(data.shape[2]), sensors): rb = ds.GetRasterBand(i + 1) rb.WriteArray(data[:, :, i].astype(np.float32)) rb.SetNoDataValue(0.0) rb.SetDescription(sensor) del ds
from osgeo import ogr, gdal shape_file = 'test.shp' output_raster = 'test.tiff' input_shp = ogr.Open(shape_file) shp_layer = input_shp.GetLayer() pixel_size = 0.01 xmin, xmax, ymin, ymax = shp_layer.GetExtent() ds = gdal.Rasterize(output_raster, shape_file, xRes=pixel_size, yRes=pixel_size, burnValues=255, outputBounds=[xmin, ymin, xmax, ymax], outputType=gdal.GDT_Byte) ds = None