Search code examples
pythonshapespixelgeotiffrasterio

ST_PixelAsPolygons rasterio


Is there a way to perform a similar function such as ST_PixelAsPolygons using rasterio? I am aware of rasterio.features.shapes but that would output the shape of similar pixels instead of the geometry of all pixels. How could I get the polygons and values of all pixels?


Solution

  • rasterio/transform.py provides an xy(transform, rows, cols, offset) function which returns the location of the grid cell at (row,col).

    The offset parameter allows you to specify each "corner" of the cell using 'ul', 'ur', 'll', 'lr'.

    You can then get the rectangular coordinates of each cell in your transform:

    rows = [i for i in range(height) for j in range(width)]
    cols = [j for i in range(height) for j in range(width)]
    corners = []
    for offset in ['ul','ur', 'lr', 'll']:
      xs, ys = rasterio.transform.xy(transform,rows,cols,offset)
      corners.append(zip(xs,ys))
    cell_rects = zip(*corners)
    cell_rects_with_indices = [
        ((row,col), rect) 
        for row,col,rect in zip(rows, cols, cell_rects)
    ]