Skip to content

Vectorize shapes (instead of pixel)  #1

@vincentsarago

Description

@vincentsarago

Just wanted to see if it was possible. Answer: Not really but at least it was fun.

from rasterio._features import _shapes
from rasterio.rio.helpers import coords
from rasterio.transform import IDENTITY


cpdef rgb_to_hex(rgba):
    return '#{:02x}{:02x}{:02x}'.format(*rgba)


cpdef bytes shapes_encoder(
    data,
    mask,
    str layer_name = "layer",
    colormap = {},
):
    cdef float x, y
    cdef tuple rgba

    mvt = Tile()
    mvt_layer = Layer(mvt, layer_name.encode())

    for (p, v) in _shapes(data, mask, connectivity=4, transform=IDENTITY):
        feature = Polygon(mvt_layer)
        xs, ys = zip(*coords(p))
        feature.add_ring(len(xs))
        for (x, y) in zip(xs, ys):
            feature.set_point(int(x), int(y))

        if colormap:
            rgba = colormap.get(v, (0, 0, 0, 0))
            feature.add_property("rgba".encode(), rgb_to_hex(rgba).encode())
        else:
            feature.add_property("value".encode(), str(v).encode())
        feature.commit()

    return mvt.serialize()

problem:

  • polygon returned by rasterio.features._shapes are quite complex and do need better handling (interior ring, multi polygon)
  • Polygon are interesting the tile bounds and should not be polygon but LineString 🤷‍♂️

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions