我正在使用 Shapely 查找具有所有正点的多边形的质心坐标。但是我得到质心坐标的负值。
from shapely.geometry import Polygon
poly = Polygon([[263.84, 256.29], [268.6, 253.5], [269.57, 260.44], [277.2, 253.1], [278.94, 252.69], [278.56, 260.02], [278.76, 275.95], [288.99, 269.15], [263.84, 256.29]])
centroid = poly.centroid
print(centroid.x, centroid.y)
我得到的答案是-120.68和-311.53,这很奇怪!我将不胜感激。
这个多边形是无效的:它有自己的交叉点,大多数空间操作都会为无效输入给出错误的结果。
您可以使用带有
is_valid
几何属性的 shapely 检查几何是否有效(下面脚本中的示例)。
您还可以使用
shapely.make_valid()
函数要求 shapely 使其有效。在这种情况下,这会将多边形转换为 3 块的多边形,并将产生合理的质心(也在下面的脚本中作为示例)。
我还直接检查了 geos 的结果,这是一个在引擎盖下强大的 c++ 库,这是一样的。
geosop -a "POLYGON ((263.84 256.29, 268.6 253.5, 269.57 260.44, 277.2 253.1, 278.94 252.69, 278.56 260.02, 278.76 275.95, 288.99 269.15, 263.84 256.29))" centroid -f wkt
POINT (-120.6802662207054 -311.5377745805696)
from matplotlib import pyplot as plt
from shapely.geometry import Polygon
import shapely.plotting
poly = Polygon(
[
[263.84, 256.29],
[268.6, 253.5],
[269.57, 260.44],
[277.2, 253.1],
[278.94, 252.69],
[278.56, 260.02],
[278.76, 275.95],
[288.99, 269.15],
[263.84, 256.29],
]
)
centroid = poly.centroid
print(poly.wkt)
print(f"centroid: {centroid.x}, {centroid.y}")
print(f"poly.is_valid: {poly.is_valid}")
shapely.plotting.plot_polygon(poly)
plt.show()
poly_valid = shapely.make_valid(poly)
centroid_valid = poly_valid.centroid
print(poly_valid.wkt)
print(f"centroid_valid: {centroid_valid.x}, {centroid_valid.y}")
print(f"poly_valid.is_valid: {poly_valid.is_valid}")
shapely.plotting.plot_polygon(poly_valid)
plt.show()
POLYGON ((263.84 256.29, 268.6 253.5, 269.57 260.44, 277.2 253.1, 278.94 252.69, 278.56 260.02, 278.76 275.95, 288.99 269.15, 263.84 256.29))
centroid: -120.6802662207054 -311.5377745805696
poly.is_valid: False
MULTIPOLYGON (((269.38634635224486 259.12602441709225, 268.6 253.5, 263.84 256.29, 269.38634635224486 259.12602441709225)), ((277.2 253.1, 270.39810534205236 259.6433691729143, 278.6079766371281 263.84133914725516, 278.56 260.02, 278.94 252.69, 277.2 253.1)), ((269.38634635224486 259.12602441709225, 269.57 260.44, 270.39810534205236 259.6433691729143, 269.38634635224486 259.12602441709225)), ((278.6079766371281 263.84133914725516, 278.76 275.95, 288.99 269.15, 278.6079766371281 263.84133914725516)))
centroid_valid: 277.9350361986902 263.6861518747837
poly_valid.is_valid: True