Converting circles into polygons in a .json file

Question:

I’ve a .json file which has annotations (in terms of circles and polygons) of objects I want to train my neural network with. The problem is however the traning code only accepts polygons from the .json file, thus giving an error since mine has circles.

Does anyone know how to convert circles into polygons?

I’ve already tried some solutions (like below) which did not work:

import json
from pprint import pprint

with open('via_region_data(val).json') as f:
    data = json.load(f)

    for attr, val in data.items():
        for attr2, val2 in val.items():
            if attr2 == 'regions':
                for attr3, val3 in val2.items():
                    if val3['shape_attributes']['name'] == 'circle':
                        cx = val3['shape_attributes']['cx']
                        cy = val3['shape_attributes']['cy']
                        r = val3['shape_attributes']['r']
                        all_points_x = [cx, cx - 1.5 * r, cx, cx + 1.5 * r, cx]
                        all_points_y = [cy - 1.5 * r, cy, cy + 1.5 * r, cy, cy - 1.5 * r]
                        val3['shape_attributes']['cx'] = all_points_x
                        val3['shape_attributes']['cy'] = all_points_y

                        val3['shape_attributes']['all_points_x'] = val3['shape_attributes'].pop('cx')
                        val3['shape_attributes']['all_points_y'] = val3['shape_attributes'].pop('cy')
                        val3['shape_attributes']['name'] = 'polygon'


pprint(data)

with open('via_region_data-val.json', 'w') as f:
    json.dump(data, f)

throwing:

Traceback (most recent call last):
  File "polygon_fixer.py", line 10, in <module>
    for attr3, val3 in val2.items():
AttributeError: 'list' object has no attribute 'items'

Any thoughts?

P.S: Well apparently some people didn’t understand that it is a .JSON file which I am trying to operate with. So here it is.

Asked By: Schütze

||

Answers:

There were two problems regarding this issue.

  1. The solution @martineau offered has to be applied. However this is not enough.

  2. The annotation tool VIA has changed JSON formatting in later versions, apparently. Now instead of a dictionary, “regions” has a list. This means, if you somehow try to read them into polygons you need to remove ‘.values()’ addition in your line, which should look like the following in any occasion.

polygons = [r['shape_attributes'] for r in a['regions']]
names = [r['region_attributes'] for r in a['regions']]

and not

polygons = [r['shape_attributes'] for r in a['regions'].values()]
names = [r['region_attributes'] for r in a['regions'].values()]
Answered By: Schütze
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.