How to find centroid snapped to grid via Shapely?

29 Views Asked by At

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.

1

There are 1 best solutions below

0
Pieter On BEST ANSWER

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)