WKT 将多边形移动到中心

问题描述 投票:0回答:1

我有一个 WKT 对象,想要将其中心移动到原点 (0,0)。 这是一个例子和我尝试过的:

from shapely import wkt

poly_str = 'POLYGON ((14.217343909259455 -2.9030822376560224, 16.003619392313993 -2.639545672126154, 16.363681477720576 -5.080080154489572, 14.577405994666037 -5.34361672001944, 14.217343909259455 -2.9030822376560224))'
geom = wkt.loads(poly_str)

normalized = geom.normalize() # this does nothing
normalized == geom # TRUE


centroid = geom.centroid
moved_geom = geom - centroid  # this seems logical, but does not achieve what I want

print(moved)
>>>> 'POLYGON ((16.003619392313993 -2.639545672126154, 16.363681477720576 -5.080080154489572, 14.577405994666037 -5.34361672001944, 14.217343909259455 -2.9030822376560224, 16.003619392313993 -2.639545672126154))'

为什么最后一个多边形没有移动质心的量,以及如何从原始多边形中获得质心位于 (0,0) 的移动多边形?

python shapely wkt
1个回答
0
投票

您实际上走在正确的轨道上,但计算移动几何体的方式存在错误。 Shapely 不直接支持移动几何体的减法运算

geom - centroid
。相反,您应该手动平移每个点的坐标。这应该是您的解决方案:

from shapely import wkt
from shapely.affinity import translate

poly_str = 'POLYGON ((14.217343909259455 -2.9030822376560224, 16.003619392313993 -2.639545672126154, 16.363681477720576 -5.080080154489572, 14.577405994666037 -5.34361672001944, 14.217343909259455 -2.9030822376560224))'
geom = wkt.loads(poly_str)

# Calculate the centroid
centroid = geom.centroid

# Calculate the translation vector
translation_vector = (-centroid.x, -centroid.y)

# Perform the translation on each point
moved_coords = [(x + translation_vector[0], y + translation_vector[1]) for x, y in geom.exterior.coords]

# Create a new geometry with the moved coordinates
moved_geom = wkt.loads('POLYGON ((' + ', '.join([f'{x} {y}' for x, y in moved_coords]) + '))')
print("Original GEOM: \n",geom.wkt)
print("Moved GEOM: \n",moved_geom.wkt)

输出:

Original GEOM: 
 POLYGON ((14.217343909259455 -2.9030822376560224, 16.003619392313993 -2.639545672126154, 16.363681477720576 -5.080080154489572, 14.577405994666037 -5.34361672001944, 14.217343909259455 -2.9030822376560224))

Moved GEOM: 
 POLYGON ((-1.0731687842305604 1.0884989584167752, 0.713106698823978 1.3520355239466437, 1.0731687842305604 -1.0884989584167744, -0.713106698823978 -1.3520355239466428, -1.0731687842305604 1.0884989584167752))
© www.soinside.com 2019 - 2024. All rights reserved.