在.json文件中将圆转换为多边形

时间:2018-09-17 07:56:13

标签: python json geometry

我有一个.json文件,其中带有要与我的神经网络一起训练的对象的注释(根据圆形和多边形)。但是问题是转换代码只接受.json文件中的多边形,由于我的有圆,因此会出错。

有人知道如何将圆形转换为多边形吗?

我已经尝试了一些无效的解决方案(如下所示):

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)

投掷:

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'

有什么想法吗?

P.S:显然,有些人不了解我正在尝试使用的.JSON文件。 So here it is

1 个答案:

答案 0 :(得分:0)

关于这个问题有两个问题。

  1. 必须使用@martineau提供的解决方案。但是,这还不够。

  2. 注释工具VIA显然已在更高版本中更改了JSON格式。现在,“区域”有一个列表,而不是字典。这意味着,如果您以某种方式尝试将它们读为多边形,则需要删除行中的'.values()'加法,在任何情况下都应类似于以下内容。

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

不是

polygons = [r['shape_attributes'] for r in a['regions'].values()]
names = [r['region_attributes'] for r in a['regions'].values()]
相关问题