2

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?

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Jun 8, 2022 at 13:13
2
  • Can you do the same in actual Python code without calling a subprocess? Commented Jun 8, 2022 at 13:36
  • I haven't figured out how to. The only thing which actually works for me at the moment is subprocess Commented Jun 8, 2022 at 13:40

1 Answer 1

5

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
answered Jun 8, 2022 at 15:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.