cppe-5 / examples /make_jsonl.py
qgyd2021's picture
[update]add code
d3a579f
raw
history blame
1.88 kB
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from collections import defaultdict
import json
from project_settings import project_path
def main():
for subset in ["train", "test"]:
filename = project_path / "data/annotations/{}.json".format(subset)
with open(filename.as_posix(), "r", encoding="utf-8") as f:
js = json.load(f)
images = js["images"]
type_ = js["type"]
annotations = js["annotations"]
categories = js["categories"]
index_to_label = dict()
for category in categories:
index = category["id"]
name = category["name"]
index_to_label[index] = name
# print(images)
image_id_to_annotations = defaultdict(list)
for annotation in annotations:
image_id = annotation["image_id"]
image_id_to_annotations[image_id].append(annotation)
with open("{}.jsonl".format(subset), "w", encoding="utf-8") as f:
for image in images:
image_id = image["id"]
annotations = image_id_to_annotations[image_id]
row = {
"image_id": image["id"],
"image": image["file_name"],
"width": image["width"],
"height": image["height"],
"objects": [
{
"id": annotation["id"],
"area": annotation["area"],
"bbox": annotation["bbox"],
"category": index_to_label[annotation["category_id"]],
} for annotation in annotations
]
}
row = json.dumps(row, ensure_ascii=False)
f.write("{}\n".format(row))
return
if __name__ == '__main__':
main()