我有以下格式的数据,即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)]

10-06 03:07