I have a COCO formatted json which if you are not familiar with COCO, is just a list of coordinates of 10 sided polygons (attached an example).
I need to create an array from these coordinates that will plot them on a 128 x 128 square as filled in polygons so that I can multiply it with another array.
I have so far tried skimage.draw polygons and matplotlib polygons. These work if I manually enter coordinates, but I don't know how to read the data in from the json and then use that as the coordinates.
Below is an example of the json.
{
"version": "4.6.0",
"flags": {},
"shapes": [
{
"label": "blob",
"points": [
[
75.14285714285714,
83.71428571428571
],
[
72.23121416791264,
82.67540136440437
],
[
70.48628641932781,
80.12350546954684
],
[
70.57457698914924,
77.03333552579737
],
[
72.46236188059122,
74.58523142065489
],
[
75.42857142857144,
73.71428571428571
],
[
78.34021440351594,
74.75317006416705
],
[
80.08514215210077,
77.30506595902457
],
[
79.99685158227935,
80.39523590277405
],
[
78.10906669083737,
82.84334000791652
]
],
"group_id": null,
"shape_type": "polygon",
"flags": {}
I have tried:
f=open('139cm_2000_frame27.json')
data=json.load(f)
shapes=data["shapes"]
for i in shapes:
print('points')
but it errors at 'points' Thank you so much!
CodePudding user response:
You can use the json library to work with json objects. If you need to load the json from a file use json.load() like so:
import json
with open('example.json', 'r') as f:
versions = json.load(f)['versions']
and use loads when from a string:
import json
json_str = '{"versions": 10}'
versions = json.loads(json_str)['versions']
CodePudding user response:
Ok, you’ve managed to get some way. You now have to navigate the ‘dicts within lists within dicts’. This code will simply print out all the coordinates of all the shapes:
f=open('139cm_2000_frame27.json')
data=json.load(f)
shapes=data["shapes"]
for i in shapes:
print(i['label']) # prints the label first
for c in i['points']:
print(c) # a list containing coordinates
(Sorry, but the single quoted strings are malformed. I’ll have to fix those later)