File size: 2,068 Bytes
d3a579f
 
 
 
bf3f8bb
 
d3a579f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf3f8bb
 
d3a579f
 
 
 
bf3f8bb
 
d3a579f
 
bf3f8bb
d3a579f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/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()