File size: 11,105 Bytes
c6cd531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""Export rmcv/armor shards to YOLO pose, COCO keypoints or SJTU LabelRoboMaster txt.



Usage:

    python export.py <input> <output> [--format yolo-pose|coco|sjtu]

                     [--classes sjtu|color|plate] [--order sjtu|tongji]

                     [--split train,test] [--source a,b]



<input> is a directory holding WebDataset .tar shards (searched recursively,

split taken from the parent folder name) or loose <key>.jpg + <key>.json pairs.



Class tables:

    sjtu   36 classes, colour * 9 + tag (blue, red, gray, purple x

           sentry, 1-5, outpost, base small, base large), as in LabelRoboMaster

    color  0 blue, 1 red

    plate  one class



Regions that must not be trained as background (role "ignore", plates whose

class cannot be decided under the chosen table, or corners not in LT, LB, RB, RT

counter-clockwise order) are painted grey (114) for yolo-pose / sjtu and written

as iscrowd=1 boxes for coco. Confirmed negatives are left as background.



Requires numpy and Pillow.

"""

import argparse
import io
import json
import tarfile
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw

COLORS = ["blue", "red", "gray", "purple"]
SJTU_TAGS = ["sentry", "1", "2", "3", "4", "5", "outpost", "base_small", "base_large"]
ORDERS = {
    "sjtu": [0, 1, 2, 3],    # LT, LB, RB, RT
    "tongji": [0, 3, 2, 1],  # TL, TR, BR, BL
}
MIRROR = [3, 2, 1, 0]  # horizontal flip: LT<->RT, LB<->RB
GREY = (114, 114, 114)
MASK_PAD = 0.15
STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
ATTR_KEYS = ["color", "size", "sticker", "flags", "corner_def", "label_type"]


def order_ok(obj):
    """LT, LB, RB, RT must run counter-clockwise in y-down image coords (negative signed area)."""
    if "corners" not in obj:
        return True
    x, y = np.asarray(obj["corners"], float).T
    return float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) < 0


def class_id(obj, table):
    if not order_ok(obj):
        return None
    if table == "plate":
        return 0
    color = obj.get("color")
    if table == "color":
        return {"blue": 0, "red": 1}.get(color)
    tag = obj.get("sticker")
    if tag == "base":
        tag = {"small": "base_small", "large": "base_large"}.get(obj.get("size"))
    if color not in COLORS or tag not in SJTU_TAGS:
        return None
    return COLORS.index(color) * 9 + SJTU_TAGS.index(tag)


def class_names(table):
    return {"plate": ["armor"], "color": ["blue", "red"]}.get(
        table, [f"{c}_{t}" for c in COLORS for t in SJTU_TAGS])


def iter_samples(root):
    """Yield (split, key, jpg_bytes, label_dict)."""
    root = Path(root)
    for tar_path in sorted(root.rglob("*.tar")):
        pending = {}
        with tarfile.open(tar_path) as tar:
            for member in tar:
                if not member.isfile():
                    continue
                key, _, ext = member.name.rpartition(".")
                parts = pending.setdefault(key, {})
                parts[ext] = tar.extractfile(member).read()
                if "jpg" in parts and "json" in parts:
                    del pending[key]
                    yield tar_path.parent.name, key, parts["jpg"], json.loads(parts["json"])
    for json_path in sorted(root.rglob("*.json")):
        jpg_path = json_path.with_suffix(".jpg")
        if jpg_path.exists():
            yield (json_path.parent.name, json_path.stem,
                   jpg_path.read_bytes(), json.loads(json_path.read_text("utf-8")))


def obj_box(obj):
    if "bbox" in obj:
        x, y, bw, bh = obj["bbox"]
        return x, y, x + bw, y + bh
    q = np.asarray(obj["corners"], float)
    return (*q.min(0), *q.max(0))


def clip_box(box, w, h):
    x0, y0, x1, y1 = box
    return (min(max(x0, 0), w - 1), min(max(y0, 0), h - 1),
            min(max(x1, 0), w - 1), min(max(y1, 0), h - 1))


def mask_box(obj, w, h):
    x0, y0, x1, y1 = obj_box(obj)
    px, py = (x1 - x0) * MASK_PAD, (y1 - y0) * MASK_PAD
    return clip_box((x0 - px, y0 - py, x1 + px, y1 + py), w, h)


def keypoints(obj, order, w, h):
    """Clipped corners (4x2), visibility (4,) and clipped box. Box-only labels get invisible points."""
    box = clip_box(obj_box(obj), w, h)
    if "corners" not in obj:
        return np.zeros((4, 2)), np.zeros(4, int), box
    q = np.asarray(obj["corners"], float)[order]
    inside = (q[:, 0] >= 0) & (q[:, 0] < w) & (q[:, 1] >= 0) & (q[:, 1] < h)
    vis = np.where(inside, np.asarray(obj.get("visibility", [2, 2, 2, 2]), int)[order], 0)
    return np.clip(q, 0, [w - 1, h - 1]), vis, box


def yolo_pose_line(cls, obj, order, w, h):
    pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
    vals = [(x0 + x1) / 2 / w, (y0 + y1) / 2 / h, (x1 - x0) / w, (y1 - y0) / h]
    for (x, y), v in zip(pts, vis):
        vals += [x / w, y / h, int(v)]
    return f"{cls} " + " ".join(f"{v:.6g}" for v in vals)


def sjtu_line(cls, obj, w, h):
    q = np.asarray(obj["corners"], float) / [w, h]
    return f"{cls} " + " ".join(f"{v:.6g}" for v in q.ravel())


def coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids):
    if cls is None:
        x0, y0, x1, y1 = mask_box(obj, w, h)
        kps, nk = [0] * 12, 0
    else:
        pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
        kps = [v for (x, y), s in zip(pts, vis) for v in (round(float(x), 2), round(float(y), 2), int(s))]
        nk = int((vis > 0).sum())
    fields = {k: obj[k] for k in ATTR_KEYS if k in obj}
    side = {"red": 0, "blue": 100}.get(obj.get("color"))
    if side is not None and obj.get("sticker") in ref_ids:
        fields["ref_id"] = ref_ids[obj["sticker"]] + side
    bw, bh = float(x1 - x0), float(y1 - y0)
    return {
        "id": ann_id, "image_id": img_id, "category_id": 1 if cls is None else cls + 1,
        "iscrowd": int(cls is None), "num_keypoints": nk, "keypoints": kps,
        "bbox": [round(float(x0), 2), round(float(y0), 2), round(bw, 2), round(bh, 2)],
        "area": round(bw * bh, 2), "attributes": fields,
    }


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("input")
    ap.add_argument("output")
    ap.add_argument("--format", choices=["yolo-pose", "coco", "sjtu"], default="yolo-pose")
    ap.add_argument("--classes", choices=["sjtu", "color", "plate"], default="sjtu")
    ap.add_argument("--order", choices=list(ORDERS), default="sjtu",
                    help="keypoint order for yolo-pose / coco (sjtu txt is always LT,LB,RB,RT)")
    ap.add_argument("--split", default="", help="comma list, e.g. train,test (default all)")
    ap.add_argument("--source", default="", help="comma list of sources (default all)")
    ap.add_argument("--quality", type=int, default=95, help="JPEG quality for masked images")
    args = ap.parse_args()

    splits = set(filter(None, args.split.split(",")))
    sources = set(filter(None, args.source.split(",")))
    order = ORDERS[args.order]
    ref_ids = {s["id"]: s["ref_id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
    out = Path(args.output)
    stats = {"images": 0, "labels": 0, "masked": 0}
    seen_splits = set()
    coco = {}
    ann_id = 0

    for split, key, jpg, label in iter_samples(args.input):
        source = label["image"].get("source") or "nosource"
        if (splits and split not in splits) or (sources and source not in sources):
            continue
        w, h = label["image"]["width"], label["image"]["height"]
        name = f"{source}__{key.replace('/', '__')}"
        img_dir = out / "images" / split
        img_dir.mkdir(parents=True, exist_ok=True)
        seen_splits.add(split)
        stats["images"] += 1

        # null means "not labelled": drop those keys so presence checks below stay simple
        objs = [{k: v for k, v in o.items() if v is not None} for o in label.get("objects", [])]
        objs = [o for o in objs if o.get("role", "positive") != "negative"]
        classes = [class_id(o, args.classes) if o.get("role", "positive") == "positive" else None
                   for o in objs]

        if args.format == "coco":
            ds = coco.setdefault(split, {"images": [], "annotations": []})
            img_id = len(ds["images"]) + 1
            ds["images"].append({**label["image"], "id": img_id, "file_name": f"{split}/{name}.jpg"})
            for obj, cls in zip(objs, classes):
                ann_id += 1
                ds["annotations"].append(coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids))
                stats["labels" if cls is not None else "masked"] += 1
            (img_dir / f"{name}.jpg").write_bytes(jpg)
            continue

        lines, masks = [], []
        for obj, cls in zip(objs, classes):
            if cls is None or (args.format == "sjtu" and "corners" not in obj):
                masks.append(mask_box(obj, w, h))
            elif args.format == "yolo-pose":
                lines.append(yolo_pose_line(cls, obj, order, w, h))
            else:
                lines.append(sjtu_line(cls, obj, w, h))
        if masks:
            im = Image.open(io.BytesIO(jpg)).convert("RGB")
            draw = ImageDraw.Draw(im)
            for box in masks:
                draw.rectangle(box, fill=GREY)
            im.save(img_dir / f"{name}.jpg", quality=args.quality)
        else:
            (img_dir / f"{name}.jpg").write_bytes(jpg)
        lbl_dir = out / "labels" / split
        lbl_dir.mkdir(parents=True, exist_ok=True)
        (lbl_dir / f"{name}.txt").write_text("".join(l + "\n" for l in lines))
        stats["labels"] += len(lines)
        stats["masked"] += len(masks)

    names = class_names(args.classes)
    flip = [order.index(MIRROR[order[j]]) for j in range(4)]
    if args.format == "coco":
        kp_names = [["LT", "LB", "RB", "RT"][i] for i in order]
        categories = [{"id": i + 1, "name": n, "keypoints": kp_names,
                       "skeleton": [[1, 2], [2, 3], [3, 4], [4, 1]]} for i, n in enumerate(names)]
        (out / "annotations").mkdir(parents=True, exist_ok=True)
        for split, ds in coco.items():
            ds["categories"] = categories
            ds["info"] = {"description": "rmcv/armor", "flip_idx": flip}
            (out / "annotations" / f"{split}.json").write_text(json.dumps(ds, ensure_ascii=False), "utf-8")
    elif args.format == "yolo-pose":
        yaml = [f"path: {out.resolve().as_posix()}"]
        yaml += [f"{'val' if s == 'test' else s}: images/{s}" for s in sorted(seen_splits)]
        yaml += ["kpt_shape: [4, 3]", f"flip_idx: {flip}",
                 "# Horizontal flips mirror the digit; train with fliplr: 0.", "names:"]
        yaml += [f"  {i}: {n}" for i, n in enumerate(names)]
        (out / "data.yaml").write_text("\n".join(yaml) + "\n")

    print(json.dumps(stats))


if __name__ == "__main__":
    main()