To write a JSON file for a dataset in the COCO format I have an RLE encoded mask with type(counts) == bytes
.
To write the dict in a JSON file I use json.dumps()
. This works for the strings, integers and floats in the dict, but not for the bytes element.
TypeError: Object of type ndarray is not JSON serializable
The dict can look like this:
annotation =
{'id': 1,
'image_id': '0002',
'category_id': 40,
'segmentation': {'size': [480, 640],
'counts': b'^cb45f>6K5J6J501O001O1O002N1O2N1O1O00O1000001O000000000000000000000000000O10000010O001O001O000000000000000000000001O003M5K4L4K5L5K4L4LQmj3'},
'area': 1923.0,
'bbox': [312, 347, 64, 37],
'iscrowd': 0}
where the value in 'counts'
is the bytes-type.
There is a way to solve the problem by converting the bytes to a string by applying:
annotation['segmentation']['counts'] = str(annotation['segmentation']['counts'])
But here is the problem: the JSON file would look like this (note that there are quotation marks (“) around the bytes):
{
"id": 1,
"image_id": "0002",
"category_id": 40,
"segmentation": {
"size": [
480,
640
],
"counts": "b'^cb45f>6K5J6J501O001O1O002N1O2N1O1O00O1000001O000000000000000000000000000O10000010O001O001O000000000000000000000001O003M5K4L4K5L5K4L4LQmj3'"
},
"area": 1923.0,
"bbox": [
312,
347,
64,
37
],
"iscrowd": 0
}
The COCO format needs a form like this though (no quotation marks around the bytes):
{
"id": 1,
"image_id": "0002",
"category_id": 40,
"segmentation": {
"size": [
480,
640
],
"counts": b'^cb45f>6K5J6J501O001O1O002N1O2N1O1O00O1000001O000000000000000000000000000O10000010O001O001O000000000000000000000001O003M5K4L4K5L5K4L4LQmj3'
},
"area": 1923.0,
"bbox": [
312,
347,
64,
37
],
"iscrowd": 0
}
Is there a way to write the JSON file in the correct format?
Leander Heine is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1