Calculating area of polygon bounding boxes

Question:

I’m trying to calculate area of polygon bounding boxes and the coordinates (x and y of polygon vertices) are saved in mask variable. 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

When I print mask, the output is:

[[[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? If is how can I solve this?

Asked By: Leon

||

Answers:

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).

xy is a two element list with all x-coordinates in first element and all y-coordinates of the polygon in second element.

area of the bounding box goes respectively from min, to max of x and y coordinates. 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. For example polygons_points_xy will better express what value is represented by the name.

Answered By: Claudio
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.