3

I am converting vector features to raster using Rasterio rasterize(). I am trying to find a way to specify the output spatial resolution. The current approach specifies the number of pixels (shape = 100, 100) in the XY dimensions.

import geopandas as gpd from rasterio.features import rasterize gdf = gpd.read_file('/path/to/polylines.shp') shape = 100, 100 transform = rasterio.transform.from_bounds(*gdf['geometry'].total_bounds, *shape) raster = rasterize( [(shape, 1) for shape in gdf['geometry']], out_shape=shape, transform=transform, fill=0, all_touched=True, dtype=rasterio.uint8) 

The following GDAL approach does what I am after, although I need to stay within the Rasterio package:

import gdal import ogr # https://stackoverflow.com/a/59892342 lines = '/path/to/poly_lines.shp' input_shp = ogr.Open(lines) output_raster = '/path/to/out_raster.tif' shp_layer = input_shp.GetLayer() pixel_size = 30 xmin, xmax, ymin, ymax = shp_layer.GetExtent() ds = gdal.Rasterize(output_raster, lines, xRes=pixel_size, yRes=pixel_size, burnValues=1, outputBounds=[xmin, ymin, xmax, ymax], allTouched=True, outputType=gdal.GDT_Byte) ds = None 

How can I specify the spatial resolution when using Rasterio rasterize()?

1 Answer 1

3

I believe it's implied by the transform, so just calculate the width and height you need when initializing that to meet your target pixel size. Something like this (untested):

import math pixel_size = 30.0 min_x, min_y, max_x, max_y = bounds = gdf['geometry'].total_bounds w_px = math.ceil((max_x - min_x) / pixel_size) h_px = math.ceil((max_y - min_y) / pixel_size) transform = rasterio.transform.from_bounds(*bounds, w_px, h_px) 

You might also be able to use transform.from_origin:

min_x, min_y, max_x, max_y = gdf['geometry'].total_bounds transform = rasterio.transform.from_origin(west=min_x, north=max_y, xsize=pixel_size, y_size=pixel_size) 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.