在 Python 中计算坐标列表的边界框

问题:

你有一个 X/Y 坐标列表,例如:

bounding_box_example.py
coords = [(6.74219, -53.57835),
          (6.74952, -53.57241),
          (6.75652, -53.56289),
          (6.74756, -53.56598),
          (6.73462, -53.57518)]

对于这些坐标,你想计算最小边界框。

解决方案 1(无 NumPy):

bounding_box_class.py
class BoundingBox(object):
    """
    2D 边界框
    """
    def __init__(self, points):
        if len(points) == 0:
            raise ValueError("无法计算空列表的边界框")
        self.minx, self.miny = float("inf"), float("inf")
        self.maxx, self.maxy = float("-inf"), float("-inf")
        for x, y in points:
            # 设置最小坐标
            if x < self.minx:
                self.minx = x
            if y < self.miny:
                self.miny = y
            # 设置最大坐标
            if x > self.maxx:
                self.maxx = x
            elif y > self.maxy:
                self.maxy = y
    @property
    def width(self):
        return self.maxx - self.minx
    @property
    def height(self):
        return self.maxy - self.miny
    def __repr__(self):
        return "BoundingBox({}, {}, {}, {})".format(
            self.minx, self.maxx, self.miny, self.maxy)

# 用法示例:
BoundingBox(coords)
# BoundingBox(6.73462, 6.75652, -53.57835, -53.56289)

通过使用 BoundingBox 类,你可以直接访问 bbox.widthbbox.height。虽然你可以在 bbox[0], bbox[1], ... 访问坐标,但你可以通过使用 bbox.minx, bbox.maxx, bbox.miny 和 bbox.maxy 访问它们来避免混淆坐标。 解决方案 2(NumPy):

使用 numpy 使管理大量坐标更高效。对于此示例,我们假设你将坐标存储在 (n,2) 形状的数组中。对于上面的示例坐标,这很容易:

bounding_box_numpy_example.py
import numpy as np
coords = np.asarray(coords)

我们可以使用 numpy 内置的 minmax 函数来计算最小/最大值,而不是自己编写。你可以查看 UliEngineering 包中的源代码。


Check out similar posts by category: Geoinformatics, Python