Interacting with raster features

A raster feature is a continguous region of like pixels. Rasterio permits extraction of features into a vector data representation and the reverse operation, "burning" vector data into a raster or image.

Extracting features

Rasterizing features

Given a source of GeoJSON-like geometry objects or objects that provide the Python Geo Interface, you can "burn" these into a raster dataset.


In [14]:
from rasterio.transform import Affine

In [15]:
def transform_from_corner(ulx, uly, dx, dy):
    return Affine.translation(ulx, uly)*Affine.scale(dx, -dy)

print transform_from_corner(bounds[0], bounds[3], 1.0/3600, 1.0/3600).to_gdal()


(119.52, 0.0002777777777777778, 0.0, -20.5, 0.0, -0.0002777777777777778)

In [16]:
from rasterio.features import rasterize
from shapely.geometry import Polygon, mapping

# image transform
bounds = (119.52, -21.6, 120.90, -20.5)
transform = transform_from_corner(bounds[0], bounds[3], 1.0/3600, 1.0/3600)

# Make raster image, burn in vector data which lies completely inside the bounding box
poly = Polygon(((120, -21), (120.5, -21), (120.5, -21.2), (120, -21.2)))
output = rasterize([poly], transform=transform, out_shape=(3961, 4969))
print output


[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

In [17]:
%matplotlib inline

In [18]:
import matplotlib.pyplot as plt

In [19]:
plt.imshow(output)


Out[19]:
<matplotlib.image.AxesImage at 0x1245e5550>

In [ ]:
import json

output = rasterize([json.dumps(mapping(poly))], transform=transform, out_shape=(3961, 4969))
print output


ERROR:rasterio:Geometry '{"type": "Polygon", "coordinates": [[[120.0, -21.0], [120.5, -21.0], [120.5, -21.2], [120.0, -21.2], [120.0, -21.0]]]}' at index 0 with value 255 skipped

In [ ]: