1

I have the following Python line to execute GDAL's rasterize function on a shapefile

subprocess.call("gdal_rasterize -te {txextent} {tyextent} -tr {resolution} -burn 1 {shapefile} {output_file}.tif")

The {output_file} is the filename of the originally ingested input file.

I'd like to save the output_file to memory, so that I can call it down in another statement later on, for example to upload to an S3 bucket.

How can I do this?

2
  • Can you do the same in actual Python code without calling a subprocess? Jun 8 at 13:36
  • I haven't figured out how to. The only thing which actually works for me at the moment is subprocess Jun 8 at 13:40

1 Answer 1

1

Here is some code which should give you an idea of how to do it. For gdal.Rasterize only the first two parameters are required. The rest of the parameters are **kwargs from RasterizeOptions . The **kwargs will be user/project specific.

import gdal

ulx, xsize, rotx, uly, roty, ysize = geotransform # from gdal's GetGeoTransform()
XSize = 100 # Raster size in pixels (columns)
YSize = 100 # Raster size in pixels (rows)
lrx = ulx + (XSize*abs(xsize)) # Calculate the lower right x coordinate
lry = uly - (YSize*abs(ysize)) # Calculate the lower right y coordinate
    
outMemRas = '/vsimem/raster_name.tif'
shpFilePath = 'shapefile_path.shp'

gdal.Rasterize(outMemRas, shpFilePath,
               outputType=gdal.GDT_Byte,
               outputSRS='EPSG:32632',
               width=XSize, height=YSize,
               outputBounds=[ulx, lry, lrx, uly],
               attribute='column_name',
               allTouched=True)
shapeRasDS = gdal.Open(outMemRas) # Open raster file in memory with gdal
shape_arr = shapeRasDS.ReadAsArray() # Read into numpy array
gdal.Unlink(outMemRas) # remove file from memory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.