computational-geometryshapelycentroidgeos

How to find centroid snapped to grid via Shapely?


When I use shapely to find a centroid, it gets me fractional values, even if I set the precision:

bbox = shapely.Polygon(coords)
shapely.set_precision(bbox, grid_size=1)
centroid = bbox.centroid
print(f'{centroid}')
# POINT (1125 1348.5)

How can I tell Shapely to snap the centroid to a grid? In this case, I'd like each dim of the point rounded to the nearest integer.


Solution

  • Use set_precision on the centroid:

    import shapely
    
    bbox = shapely.box(0, 0, 9, 9)
    centroid = bbox.centroid
    print(f"{centroid}")
    # POINT (4.5 4.5)
    
    centroid_rounded = shapely.set_precision(centroid, grid_size=1)
    print(f"{centroid_rounded}")
    # POINT (5 5)