File size: 5,699 Bytes
16aa0e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import random
from collections import defaultdict
from pathlib import Path
from typing import Dict, List

import fire
import numpy as np
from PIL import Image
from sahi.utils.coco import Coco, CocoAnnotation, CocoCategory, CocoImage
from sahi.utils.file import load_json, save_json
from tqdm import tqdm

# fix the seed
random.seed(13)


def xview_to_coco(
    train_images_dir,
    train_geojson_path,
    output_dir,
    train_split_rate=0.75,
    category_id_remapping=None,
):
    """
    Converts visdrone-det annotations into coco annotation.

    Args:
        train_images_dir: str
            'train_images' folder directory
        train_geojson_path: str
            'xView_train.geojson' file path
        output_dir: str
            Output folder directory
        train_split_rate: bool
            Train split ratio
        category_id_remapping: dict
            Used for selecting desired category ids and mapping them.
            If not provided, xView mapping will be used.
            format: str(id) to str(id)
    """

    # init vars
    category_id_to_name = {}
    with open("src/xview/xview_class_labels.txt", encoding="utf8") as f:
        lines = f.readlines()
    for line in lines:
        category_id = line.split(":")[0]
        category_name = line.split(":")[1].replace("\n", "")
        category_id_to_name[category_id] = category_name

    if category_id_remapping is None:
        category_id_remapping = load_json("src/xview/category_id_mapping.json")
    category_id_remapping

    # init coco object
    coco = Coco()
    # append categories
    for category_id, category_name in category_id_to_name.items():
        if category_id in category_id_remapping.keys():
            remapped_category_id = category_id_remapping[category_id]
            coco.add_category(
                CocoCategory(id=int(remapped_category_id), name=category_name)
            )

    # parse xview data
    coords, chips, classes, image_name_to_annotation_ind = get_labels(
        train_geojson_path
    )
    image_name_list = get_ordered_image_name_list(image_name_to_annotation_ind)

    # convert xView data to COCO format
    for image_name in tqdm(image_name_list, "Converting xView data into COCO format"):
        # create coco image object
        width, height = Image.open(Path(train_images_dir) / image_name).size
        coco_image = CocoImage(file_name=image_name, height=height, width=width)

        annotation_ind_list = image_name_to_annotation_ind[image_name]

        # iterate over image annotations
        for annotation_ind in annotation_ind_list:
            bbox = coords[annotation_ind].tolist()
            category_id = str(int(classes[annotation_ind].item()))
            coco_bbox = [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]]
            if category_id in category_id_remapping.keys():
                category_name = category_id_to_name[category_id]
                remapped_category_id = category_id_remapping[category_id]
            else:
                continue
            # create coco annotation and append it to coco image
            coco_annotation = CocoAnnotation(
                bbox=coco_bbox,
                category_id=int(remapped_category_id),
                category_name=category_name,
            )
            if coco_annotation.area > 0:
                coco_image.add_annotation(coco_annotation)
        coco.add_image(coco_image)

    result = coco.split_coco_as_train_val(train_split_rate=train_split_rate)

    train_json_path = Path(output_dir) / "train.json"
    val_json_path = Path(output_dir) / "val.json"
    save_json(data=result["train_coco"].json, save_path=train_json_path)
    save_json(data=result["val_coco"].json, save_path=val_json_path)


def get_ordered_image_name_list(image_name_to_annotation_ind: Dict):
    image_name_list: List[str] = list(image_name_to_annotation_ind.keys())

    def get_image_ind(image_name: str):
        return int(image_name.split(".")[0])

    image_name_list.sort(key=get_image_ind)

    return image_name_list


def get_labels(fname):
    """
    Gets label data from a geojson label file
    Args:
        fname: file path to an xView geojson label file
    Output:
        Returns three arrays: coords, chips, and classes corresponding to the
            coordinates, file-names, and classes for each ground truth.
    Modified from https://github.com/DIUx-xView.
    """
    data = load_json(fname)

    coords = np.zeros((len(data["features"]), 4))
    chips = np.zeros((len(data["features"])), dtype="object")
    classes = np.zeros((len(data["features"])))
    image_name_to_annotation_ind = defaultdict(list)

    for i in tqdm(range(len(data["features"])), "Parsing xView data"):
        if data["features"][i]["properties"]["bounds_imcoords"] != []:
            b_id = data["features"][i]["properties"]["image_id"]
            # https://github.com/DIUx-xView/xView1_baseline/issues/3
            if b_id == "1395.tif":
                continue
            val = np.array(
                [
                    int(num)
                    for num in data["features"][i]["properties"][
                        "bounds_imcoords"
                    ].split(",")
                ]
            )
            chips[i] = b_id
            classes[i] = data["features"][i]["properties"]["type_id"]

            image_name_to_annotation_ind[b_id].append(i)

            if val.shape[0] != 4:
                print("Issues at %d!" % i)
            else:
                coords[i] = val
        else:
            chips[i] = "None"

    return coords, chips, classes, image_name_to_annotation_ind


if __name__ == "__main__":
    fire.Fire(xview_to_coco)