Python:定义最小外接矩形

标签 python list numpy 2d gis

我有以下格式的数据,即 2d x,y 坐标列表:

[(6, 7), (2, 4), (8, 9), (3, 7), (5, 4), (9, 9)]

我正在尝试遍历列表以找到格式为 [(minx,miny),(maxx,miny),(maxx,maxy),(minx,maxy)] 的最小边界框

因此我编写了以下代码,但它似乎不起作用。可能与我没有向其传递数组而不是列表这一事实有关。输入和代码如下,打印坐标返回前面提到的列表:

os.chdir("filepath")
with open ('file.csv') as csvfile:
    coords = [(int(x), int(y)) for x, y in csv.reader(csvfile, delimiter= ',')]
print coords


def bounding_box(coords):
    min_x, min_y = numpy.min(coords[0], axis=0)
    max_x, max_y = numpy.max(coords[0], axis=0)
    return numpy.array(
        [(min_x, min_y), (max_x, min_y), (max_x, max_y), (min_x, max_y)])

有人能给我指出正确的方向吗?如果上面的整个代码没有帮助,请随意忽略。

最佳答案

为什么不直接使用四个计数器迭代列表:min_xmin_ymax_xmax_y

def bounding_box(coords):

  min_x = 100000 # start with something much higher than expected min
  min_y = 100000
  max_x = -100000 # start with something much lower than expected max
  max_y = -100000

  for item in coords:
    if item[0] < min_x:
      min_x = item[0]

    if item[0] > max_x:
      max_x = item[0]

    if item[1] < min_y:
      min_y = item[1]

    if item[1] > max_y:
      max_y = item[1]

  return [(min_x,min_y),(max_x,min_y),(max_x,max_y),(min_x,max_y)]

使用您的示例输入:

bounding_box([(6, 7), (2, 4), (8, 9), (3, 7), (5, 4), (9, 9)])
>> [(2, 4), (9, 4), (9, 9), (2, 9)]

关于Python:定义最小外接矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20808393/

相关文章:

list - Haskell 持久列表

Python 列表追加

python - 子类化 numpy ndarray 在 __getitem__ 处中断

python - 美汤问题

list - 如何使用 Scheme 的 Map 函数将两个列表传递给一个函数?

python - 连接两个大的 numpy 二维数组

python - 将 unicode 元素读入 numpy 数组

python - RBF 层 - 理解困难

python - 激活venv时权限被拒绝

python - 调试python时的vscode工作目录