如何计算边界框的中心点?

3

我想要使用给定的点计算边界框的中心点。

(50.607041876988994, -1.3187316344406208, 52.40735812301099, 1.5737316344406207)

这是我用Python编写的代码。

def center_geolocation(geolocations):
    """
    Provide a relatively accurate center lat, lon returned as a list pair, given
    a list of list pairs.
    ex: in: geolocations = ((lat1,lon1), (lat2,lon2),)
        out: (center_lat, center_lon)
    """
    x = 0
    y = 0
    z = 0

    for lat, lon in geolocations:
        lat = float(lat)
        lon = float(lon)
        x += cos(lat) * cos(lon)
        y += cos(lat) * sin(lon)
        z += sin(lat)

    x = float(x / len(geolocations))
    y = float(y / len(geolocations))
    z = float(z / len(geolocations))

    return (atan2(y, x), atan2(z, sqrt(x * x + y * y)))

然而,我一直遇到这个错误。
line 64, in center_geolocation
    for lat, lon in geolocations:
TypeError: 'float' object is not iterable

有人能解释一下我做错了什么吗?或者可以纠正我可能犯的错误吗?

谢谢:)


你将什么作为参数传递给函数? - Alberto Bonsanto
我正在尝试传递我计算出的边界框的这些坐标 (50.607041876988994, -1.3187316344406208, 52.40735812301099, 1.5737316344406207)。 - Mr_Shoryuken
2个回答

2
from math import *

def center_geolocation(geolocations):
    """
    Provide a relatively accurate center lat, lon returned as a list pair, given
    a list of list pairs.
    ex: in: geolocations = ((lat1,lon1), (lat2,lon2),)
        out: (center_lat, center_lon)
"""
x = 0
y = 0
z = 0

for lat, lon in geolocations:
    lat = float(lat)
    lon = float(lon)
    x += cos(lat) * cos(lon)
    y += cos(lat) * sin(lon)
    z += sin(lat)

x = float(x / len(geolocations))
y = float(y / len(geolocations))
z = float(z / len(geolocations))

return (atan2(y, x), atan2(z, sqrt(x * x + y * y)))


center_geolocation( 
 ((50.607041876988994, -1.3187316344406208),   
  (52.40735812301099, 1.5737316344406207)))

你提供的例子中没有浮点数错误...我不喜欢输出结果,但这不是问题。

2
一个问题,它打印出了(-1.4093883217883079, 0.6741482698408712),而应该打印出51.51608899635712, 0.09891956707558282,你知道我可能哪里出错了吗? - Mr_Shoryuken
1
这个解决方案似乎在度数上进行了所有的计算,我认为它们应该先转换为弧度,然后在最后再转换回度数,例如在开头 lat = float(lat) * pi / 180(对于lon也是同样的)以及 atan2(y, x) * 180 / pi(对于经度也是同样的)。 - tenor528
1
此外,我认为输出应该是(center_lon, center_lat),而不是描述中的内容。 - tenor528

1
一个使用shapely库的解决方案:
from shapely.geometry import box

bounds = (-1.3187316344406208, 50.607041876988994, 1.5737316344406207, 52.40735812301099)
polygon = box(*bounds)

print(polygon.centroid.x, polygon.centroid.y)

bounds被定义为(西南经度,西南纬度,东北经度,东北纬度)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接