cppe-5 / examples /make_jsonl.py
qgyd2021's picture
[update]add data
bf3f8bb
raw
history blame
2.07 kB
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from collections import defaultdict
import json
import os
from pathlib import Path
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)
to_filename = project_path / "data/annotations/{}.jsonl".format(subset)
with open(to_filename.as_posix(), "w", encoding="utf-8") as f:
for image in images:
image_id = image["id"]
annotations = image_id_to_annotations[image_id]
image_path = Path("data/images") / image["file_name"]
row = {
"image_id": image["id"],
"image": image_path.as_posix(),
"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()