gpt4 book ai didi

Python:定义最小外接矩形

转载 作者:太空宇宙 更新时间:2023-11-03 18:39:36 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com