Don Mclachlan
Don Mclachlan

Reputation: 449

rasterio rasterize shapely ploygons and save plot to file

Ultimately I will create a bunch of rasters from a bunch of building polygons in a geopandas dataframe. But this is preliminary testing.

>>> import shapely
>>> import shapely.geometry
>>> import rasterio.features
>>> poly1 = shapely.geometry.Polygon([(2,2), (6,2), (6,6), (2,6)])
>>> poly2 = shapely.geometry.Polygon([(4,4), (8,4), (8,8), (4,8)])
>>> rasterio.features.rasterize([poly1,poly2], out_shape=(10, 10), all_touched=True)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 1, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>>> bldgs = rasterio.features.rasterize([poly1,poly2], out_shape=(10, 10), all_touched=True)
>>> import rasterio.plot
>>> rasterio.plot.show(bldgs)

enter image description here

I'd like to save images like this on the fly instead of showing them. It seems rasterio does not have a savefig() method. (I've seen tif plotting but no combination I've tried has worked.)

I bet it is simple, but how to get there from here?

Or should I use matplotlib.pyplot directly instead?

Upvotes: 2

Views: 398

Answers (1)

Pieter
Pieter

Reputation: 1516

I indeed use matplotlib.pyplot directly for that, like this:

from matplotlib import pyplot as plt
import shapely
import shapely.geometry
import rasterio.features
import rasterio.plot

poly1 = shapely.geometry.Polygon([(2, 2), (6, 2), (6, 6), (2, 6)])
poly2 = shapely.geometry.Polygon([(4, 4), (8, 4), (8, 8), (4, 8)])
rasterio.features.rasterize([poly1, poly2], out_shape=(10, 10), all_touched=True)
bldgs = rasterio.features.rasterize(
    [poly1, poly2], out_shape=(10, 10), all_touched=True
)

fig, ax = plt.subplots()
rasterio.plot.show(bldgs, ax=ax)
plt.savefig("test.png")

Upvotes: 1

Related Questions