简体   繁体   English

计算多边形边界框的面积

[英]Calculating area of polygon bounding boxes

I'm trying to calculate area of polygon bounding boxes and the coordinates (x and y of polygon vertices) are saved in mask variable.我正在尝试计算多边形边界框的面积,坐标(多边形顶点的 x 和 y)保存在 mask 变量中。 This is my code:这是我的代码:

f = open('train_labels.json')
data = json.load(f)
mask = []
for i in data.keys(): # iterate over all images in dataset 
    for j in data[i]: # iterate over json to access points (coordinates)
        mask.append(j['points'])
        print(mask)
        area = (mask[:, 3] - mask[:, 1]) * (mask[:, 2] - mask[:, 0])
        print(area)

Error that shows me is: TypeError: list indices must be integers or slices, not tuple向我显示的错误是: TypeError: list indices must be integers or slices, not tuple

When I print mask, the output is:当我打印面具时,output 是:

[[[141, 199], [237, 201], [313, 236], [357, 283], [359, 300], [309, 261], [233, 230], [140, 231]], [[25, 13], [57, 71], [26, 92], [0, 34]], [[264, 21], [296, 0], [300, 9], [272, 31]], [[322, 0], [351, 25], [340, 31], [317, 9]]] [[[141, 199], [237, 201], [313, 236], [357, 283], [359, 300], [309, 261], [233, 230], [140, 231]], [[25, 13], [57, 71], [26, 92], [0, 34]], [[264, 21], [296, 0], [300, 9], [272, 31]], [[322, 0], [351, 25], [340, 31], [317, 9]], [[287, 71]]] etc...

So between tripple square brackets...,[317, 9]]] [[[141, 199],... doesn't exist comma (,) and is that the problem?所以在三个方括号之间...,[317, 9]]] [[[141, 199],... 逗号 (,) 不存在,这是问题所在吗? If is how can I solve this?如果是我该如何解决这个问题?

Try:尝试:

        xy = list(zip(*mask[-1]))
        area = (max(xy[0])-min(xy[0]))*(max(xy[1])-min(xy[1]))

mask[-1] will get the last item appended to mask (if you need the mask storing all the items). mask[-1]将获得附加到掩码的最后一项(如果您需要掩码存储所有项目)。

xy is a two element list with all x-coordinates in first element and all y-coordinates of the polygon in second element. xy是一个双元素列表,第一个元素中的所有 x 坐标和第二个元素中的多边形的所有 y 坐标。

area of the bounding box goes respectively from min, to max of x and y coordinates.边界框的area分别从最小值到 x 和 y 坐标的最大值。 The 'polygon' can have any number of points, but at least one. “多边形”可以有任意数量的点,但至少有一个。

I suggest you choose another name for mask as the name 'mask' suggest a use as mask which is not the case.我建议您为mask选择另一个名称,因为名称“面具”建议用作面具,但事实并非如此。 For example polygons_points_xy will better express what value is represented by the name.例如polygons_points_xy将更好地表达名称所代表的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM