Datasets:
Uniform label schema (missing fields as null) so the viewer infers one structure; pack.py normalizes
Browse files
README.md
CHANGED
|
@@ -66,7 +66,7 @@ tools/export.py 导出为训练格式
|
|
| 66 |
}
|
| 67 |
```
|
| 68 |
|
| 69 |
-
`corners` 和 `bbox` 至少有一个,其余字段有就填,没有就省略。缺失的字段在训练时只是该项不计损失,不影响其他字段。
|
| 70 |
|
| 71 |
| 字段 | 取值 |
|
| 72 |
|---|---|
|
|
|
|
| 66 |
}
|
| 67 |
```
|
| 68 |
|
| 69 |
+
`corners` 和 `bbox` 至少有一个,其余字段有就填,没有就省略或写 `null`。缺失的字段在训练时只是该项不计损失,不影响其他字段。`tools/pack.py` 打包时会把每个对象补全为同一组字段,缺失的写成 `null`。
|
| 70 |
|
| 71 |
| 字段 | 取值 |
|
| 72 |
|---|---|
|
data/qdu_damo/train/qdu_damo-train-00000.tar
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:52c94bec06c3eee80897bae5477f102317fe8655c569bc3296f8dc7864ab951d
|
| 3 |
+
size 215388160
|
data/qdu_gimbal_0507/train/qdu_gimbal_0507-train-00000.tar
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5c699734af383a63bde07549aecf3b1f01ee83f7bd977b767756757d1f7414ce
|
| 3 |
+
size 144414720
|
data/qdu_gimbal_0509/train/qdu_gimbal_0509-train-00000.tar
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3949562cea031db5d5da955a6c97fb8e890867976180d881ebb73d48c10d74f4
|
| 3 |
+
size 261437440
|
tools/export.py
CHANGED
|
@@ -1,257 +1,259 @@
|
|
| 1 |
-
"""Export rmcv/armor shards to YOLO pose, COCO keypoints or SJTU LabelRoboMaster txt.
|
| 2 |
-
|
| 3 |
-
Usage:
|
| 4 |
-
python export.py <input> <output> [--format yolo-pose|coco|sjtu]
|
| 5 |
-
[--classes sjtu|color|plate] [--order sjtu|tongji]
|
| 6 |
-
[--split train,test] [--source a,b]
|
| 7 |
-
|
| 8 |
-
<input> is a directory holding WebDataset .tar shards (searched recursively,
|
| 9 |
-
split taken from the parent folder name) or loose <key>.jpg + <key>.json pairs.
|
| 10 |
-
|
| 11 |
-
Class tables:
|
| 12 |
-
sjtu 36 classes, colour * 9 + tag (blue, red, gray, purple x
|
| 13 |
-
sentry, 1-5, outpost, base small, base large), as in LabelRoboMaster
|
| 14 |
-
color 0 blue, 1 red
|
| 15 |
-
plate one class
|
| 16 |
-
|
| 17 |
-
Regions that must not be trained as background (role "ignore", plates whose
|
| 18 |
-
class cannot be decided under the chosen table, or corners not in LT, LB, RB, RT
|
| 19 |
-
counter-clockwise order) are painted grey (114) for yolo-pose / sjtu and written
|
| 20 |
-
as iscrowd=1 boxes for coco. Confirmed negatives are left as background.
|
| 21 |
-
|
| 22 |
-
Requires numpy and Pillow.
|
| 23 |
-
"""
|
| 24 |
-
|
| 25 |
-
import argparse
|
| 26 |
-
import io
|
| 27 |
-
import json
|
| 28 |
-
import tarfile
|
| 29 |
-
from pathlib import Path
|
| 30 |
-
|
| 31 |
-
import numpy as np
|
| 32 |
-
from PIL import Image, ImageDraw
|
| 33 |
-
|
| 34 |
-
COLORS = ["blue", "red", "gray", "purple"]
|
| 35 |
-
SJTU_TAGS = ["sentry", "1", "2", "3", "4", "5", "outpost", "base_small", "base_large"]
|
| 36 |
-
ORDERS = {
|
| 37 |
-
"sjtu": [0, 1, 2, 3], # LT, LB, RB, RT
|
| 38 |
-
"tongji": [0, 3, 2, 1], # TL, TR, BR, BL
|
| 39 |
-
}
|
| 40 |
-
MIRROR = [3, 2, 1, 0] # horizontal flip: LT<->RT, LB<->RB
|
| 41 |
-
GREY = (114, 114, 114)
|
| 42 |
-
MASK_PAD = 0.15
|
| 43 |
-
STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
|
| 44 |
-
ATTR_KEYS = ["color", "size", "sticker", "flags", "corner_def", "label_type"]
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def order_ok(obj):
|
| 48 |
-
"""LT, LB, RB, RT must run counter-clockwise in y-down image coords (negative signed area)."""
|
| 49 |
-
if "corners" not in obj:
|
| 50 |
-
return True
|
| 51 |
-
x, y = np.asarray(obj["corners"], float).T
|
| 52 |
-
return float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) < 0
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def class_id(obj, table):
|
| 56 |
-
if not order_ok(obj):
|
| 57 |
-
return None
|
| 58 |
-
if table == "plate":
|
| 59 |
-
return 0
|
| 60 |
-
color = obj.get("color")
|
| 61 |
-
if table == "color":
|
| 62 |
-
return {"blue": 0, "red": 1}.get(color)
|
| 63 |
-
tag = obj.get("sticker")
|
| 64 |
-
if tag == "base":
|
| 65 |
-
tag = {"small": "base_small", "large": "base_large"}.get(obj.get("size"))
|
| 66 |
-
if color not in COLORS or tag not in SJTU_TAGS:
|
| 67 |
-
return None
|
| 68 |
-
return COLORS.index(color) * 9 + SJTU_TAGS.index(tag)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def class_names(table):
|
| 72 |
-
return {"plate": ["armor"], "color": ["blue", "red"]}.get(
|
| 73 |
-
table, [f"{c}_{t}" for c in COLORS for t in SJTU_TAGS])
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def iter_samples(root):
|
| 77 |
-
"""Yield (split, key, jpg_bytes, label_dict)."""
|
| 78 |
-
root = Path(root)
|
| 79 |
-
for tar_path in sorted(root.rglob("*.tar")):
|
| 80 |
-
pending = {}
|
| 81 |
-
with tarfile.open(tar_path) as tar:
|
| 82 |
-
for member in tar:
|
| 83 |
-
if not member.isfile():
|
| 84 |
-
continue
|
| 85 |
-
key, _, ext = member.name.rpartition(".")
|
| 86 |
-
parts = pending.setdefault(key, {})
|
| 87 |
-
parts[ext] = tar.extractfile(member).read()
|
| 88 |
-
if "jpg" in parts and "json" in parts:
|
| 89 |
-
del pending[key]
|
| 90 |
-
yield tar_path.parent.name, key, parts["jpg"], json.loads(parts["json"])
|
| 91 |
-
for json_path in sorted(root.rglob("*.json")):
|
| 92 |
-
jpg_path = json_path.with_suffix(".jpg")
|
| 93 |
-
if jpg_path.exists():
|
| 94 |
-
yield (json_path.parent.name, json_path.stem,
|
| 95 |
-
jpg_path.read_bytes(), json.loads(json_path.read_text("utf-8")))
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def obj_box(obj):
|
| 99 |
-
if "bbox" in obj:
|
| 100 |
-
x, y, bw, bh = obj["bbox"]
|
| 101 |
-
return x, y, x + bw, y + bh
|
| 102 |
-
q = np.asarray(obj["corners"], float)
|
| 103 |
-
return (*q.min(0), *q.max(0))
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
def clip_box(box, w, h):
|
| 107 |
-
x0, y0, x1, y1 = box
|
| 108 |
-
return (min(max(x0, 0), w - 1), min(max(y0, 0), h - 1),
|
| 109 |
-
min(max(x1, 0), w - 1), min(max(y1, 0), h - 1))
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
def mask_box(obj, w, h):
|
| 113 |
-
x0, y0, x1, y1 = obj_box(obj)
|
| 114 |
-
px, py = (x1 - x0) * MASK_PAD, (y1 - y0) * MASK_PAD
|
| 115 |
-
return clip_box((x0 - px, y0 - py, x1 + px, y1 + py), w, h)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def keypoints(obj, order, w, h):
|
| 119 |
-
"""Clipped corners (4x2), visibility (4,) and clipped box. Box-only labels get invisible points."""
|
| 120 |
-
box = clip_box(obj_box(obj), w, h)
|
| 121 |
-
if "corners" not in obj:
|
| 122 |
-
return np.zeros((4, 2)), np.zeros(4, int), box
|
| 123 |
-
q = np.asarray(obj["corners"], float)[order]
|
| 124 |
-
inside = (q[:, 0] >= 0) & (q[:, 0] < w) & (q[:, 1] >= 0) & (q[:, 1] < h)
|
| 125 |
-
vis = np.where(inside, np.asarray(obj.get("visibility", [2, 2, 2, 2]), int)[order], 0)
|
| 126 |
-
return np.clip(q, 0, [w - 1, h - 1]), vis, box
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
def yolo_pose_line(cls, obj, order, w, h):
|
| 130 |
-
pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
|
| 131 |
-
vals = [(x0 + x1) / 2 / w, (y0 + y1) / 2 / h, (x1 - x0) / w, (y1 - y0) / h]
|
| 132 |
-
for (x, y), v in zip(pts, vis):
|
| 133 |
-
vals += [x / w, y / h, int(v)]
|
| 134 |
-
return f"{cls} " + " ".join(f"{v:.6g}" for v in vals)
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
def sjtu_line(cls, obj, w, h):
|
| 138 |
-
q = np.asarray(obj["corners"], float) / [w, h]
|
| 139 |
-
return f"{cls} " + " ".join(f"{v:.6g}" for v in q.ravel())
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
def coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids):
|
| 143 |
-
if cls is None:
|
| 144 |
-
x0, y0, x1, y1 = mask_box(obj, w, h)
|
| 145 |
-
kps, nk = [0] * 12, 0
|
| 146 |
-
else:
|
| 147 |
-
pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
|
| 148 |
-
kps = [v for (x, y), s in zip(pts, vis) for v in (round(float(x), 2), round(float(y), 2), int(s))]
|
| 149 |
-
nk = int((vis > 0).sum())
|
| 150 |
-
fields = {k: obj[k] for k in ATTR_KEYS if k in obj}
|
| 151 |
-
side = {"red": 0, "blue": 100}.get(obj.get("color"))
|
| 152 |
-
if side is not None and obj.get("sticker") in ref_ids:
|
| 153 |
-
fields["ref_id"] = ref_ids[obj["sticker"]] + side
|
| 154 |
-
bw, bh = float(x1 - x0), float(y1 - y0)
|
| 155 |
-
return {
|
| 156 |
-
"id": ann_id, "image_id": img_id, "category_id": 1 if cls is None else cls + 1,
|
| 157 |
-
"iscrowd": int(cls is None), "num_keypoints": nk, "keypoints": kps,
|
| 158 |
-
"bbox": [round(float(x0), 2), round(float(y0), 2), round(bw, 2), round(bh, 2)],
|
| 159 |
-
"area": round(bw * bh, 2), "attributes": fields,
|
| 160 |
-
}
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
def main():
|
| 164 |
-
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 165 |
-
ap.add_argument("input")
|
| 166 |
-
ap.add_argument("output")
|
| 167 |
-
ap.add_argument("--format", choices=["yolo-pose", "coco", "sjtu"], default="yolo-pose")
|
| 168 |
-
ap.add_argument("--classes", choices=["sjtu", "color", "plate"], default="sjtu")
|
| 169 |
-
ap.add_argument("--order", choices=list(ORDERS), default="sjtu",
|
| 170 |
-
help="keypoint order for yolo-pose / coco (sjtu txt is always LT,LB,RB,RT)")
|
| 171 |
-
ap.add_argument("--split", default="", help="comma list, e.g. train,test (default all)")
|
| 172 |
-
ap.add_argument("--source", default="", help="comma list of sources (default all)")
|
| 173 |
-
ap.add_argument("--quality", type=int, default=95, help="JPEG quality for masked images")
|
| 174 |
-
args = ap.parse_args()
|
| 175 |
-
|
| 176 |
-
splits = set(filter(None, args.split.split(",")))
|
| 177 |
-
sources = set(filter(None, args.source.split(",")))
|
| 178 |
-
order = ORDERS[args.order]
|
| 179 |
-
ref_ids = {s["id"]: s["ref_id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
|
| 180 |
-
out = Path(args.output)
|
| 181 |
-
stats = {"images": 0, "labels": 0, "masked": 0}
|
| 182 |
-
seen_splits = set()
|
| 183 |
-
coco = {}
|
| 184 |
-
ann_id = 0
|
| 185 |
-
|
| 186 |
-
for split, key, jpg, label in iter_samples(args.input):
|
| 187 |
-
source = label["image"].get("source"
|
| 188 |
-
if (splits and split not in splits) or (sources and source not in sources):
|
| 189 |
-
continue
|
| 190 |
-
w, h = label["image"]["width"], label["image"]["height"]
|
| 191 |
-
name = f"{source}__{key.replace('/', '__')}"
|
| 192 |
-
img_dir = out / "images" / split
|
| 193 |
-
img_dir.mkdir(parents=True, exist_ok=True)
|
| 194 |
-
seen_splits.add(split)
|
| 195 |
-
stats["images"] += 1
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
ds
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
lines.append(
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
(img_dir / f"{name}.jpg"
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
yaml
|
| 249 |
-
|
| 250 |
-
yaml += [f"
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export rmcv/armor shards to YOLO pose, COCO keypoints or SJTU LabelRoboMaster txt.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python export.py <input> <output> [--format yolo-pose|coco|sjtu]
|
| 5 |
+
[--classes sjtu|color|plate] [--order sjtu|tongji]
|
| 6 |
+
[--split train,test] [--source a,b]
|
| 7 |
+
|
| 8 |
+
<input> is a directory holding WebDataset .tar shards (searched recursively,
|
| 9 |
+
split taken from the parent folder name) or loose <key>.jpg + <key>.json pairs.
|
| 10 |
+
|
| 11 |
+
Class tables:
|
| 12 |
+
sjtu 36 classes, colour * 9 + tag (blue, red, gray, purple x
|
| 13 |
+
sentry, 1-5, outpost, base small, base large), as in LabelRoboMaster
|
| 14 |
+
color 0 blue, 1 red
|
| 15 |
+
plate one class
|
| 16 |
+
|
| 17 |
+
Regions that must not be trained as background (role "ignore", plates whose
|
| 18 |
+
class cannot be decided under the chosen table, or corners not in LT, LB, RB, RT
|
| 19 |
+
counter-clockwise order) are painted grey (114) for yolo-pose / sjtu and written
|
| 20 |
+
as iscrowd=1 boxes for coco. Confirmed negatives are left as background.
|
| 21 |
+
|
| 22 |
+
Requires numpy and Pillow.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import io
|
| 27 |
+
import json
|
| 28 |
+
import tarfile
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
from PIL import Image, ImageDraw
|
| 33 |
+
|
| 34 |
+
COLORS = ["blue", "red", "gray", "purple"]
|
| 35 |
+
SJTU_TAGS = ["sentry", "1", "2", "3", "4", "5", "outpost", "base_small", "base_large"]
|
| 36 |
+
ORDERS = {
|
| 37 |
+
"sjtu": [0, 1, 2, 3], # LT, LB, RB, RT
|
| 38 |
+
"tongji": [0, 3, 2, 1], # TL, TR, BR, BL
|
| 39 |
+
}
|
| 40 |
+
MIRROR = [3, 2, 1, 0] # horizontal flip: LT<->RT, LB<->RB
|
| 41 |
+
GREY = (114, 114, 114)
|
| 42 |
+
MASK_PAD = 0.15
|
| 43 |
+
STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
|
| 44 |
+
ATTR_KEYS = ["color", "size", "sticker", "flags", "corner_def", "label_type"]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def order_ok(obj):
|
| 48 |
+
"""LT, LB, RB, RT must run counter-clockwise in y-down image coords (negative signed area)."""
|
| 49 |
+
if "corners" not in obj:
|
| 50 |
+
return True
|
| 51 |
+
x, y = np.asarray(obj["corners"], float).T
|
| 52 |
+
return float(np.dot(x, np.roll(y, -1)) - np.dot(y, np.roll(x, -1))) < 0
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def class_id(obj, table):
|
| 56 |
+
if not order_ok(obj):
|
| 57 |
+
return None
|
| 58 |
+
if table == "plate":
|
| 59 |
+
return 0
|
| 60 |
+
color = obj.get("color")
|
| 61 |
+
if table == "color":
|
| 62 |
+
return {"blue": 0, "red": 1}.get(color)
|
| 63 |
+
tag = obj.get("sticker")
|
| 64 |
+
if tag == "base":
|
| 65 |
+
tag = {"small": "base_small", "large": "base_large"}.get(obj.get("size"))
|
| 66 |
+
if color not in COLORS or tag not in SJTU_TAGS:
|
| 67 |
+
return None
|
| 68 |
+
return COLORS.index(color) * 9 + SJTU_TAGS.index(tag)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def class_names(table):
|
| 72 |
+
return {"plate": ["armor"], "color": ["blue", "red"]}.get(
|
| 73 |
+
table, [f"{c}_{t}" for c in COLORS for t in SJTU_TAGS])
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def iter_samples(root):
|
| 77 |
+
"""Yield (split, key, jpg_bytes, label_dict)."""
|
| 78 |
+
root = Path(root)
|
| 79 |
+
for tar_path in sorted(root.rglob("*.tar")):
|
| 80 |
+
pending = {}
|
| 81 |
+
with tarfile.open(tar_path) as tar:
|
| 82 |
+
for member in tar:
|
| 83 |
+
if not member.isfile():
|
| 84 |
+
continue
|
| 85 |
+
key, _, ext = member.name.rpartition(".")
|
| 86 |
+
parts = pending.setdefault(key, {})
|
| 87 |
+
parts[ext] = tar.extractfile(member).read()
|
| 88 |
+
if "jpg" in parts and "json" in parts:
|
| 89 |
+
del pending[key]
|
| 90 |
+
yield tar_path.parent.name, key, parts["jpg"], json.loads(parts["json"])
|
| 91 |
+
for json_path in sorted(root.rglob("*.json")):
|
| 92 |
+
jpg_path = json_path.with_suffix(".jpg")
|
| 93 |
+
if jpg_path.exists():
|
| 94 |
+
yield (json_path.parent.name, json_path.stem,
|
| 95 |
+
jpg_path.read_bytes(), json.loads(json_path.read_text("utf-8")))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def obj_box(obj):
|
| 99 |
+
if "bbox" in obj:
|
| 100 |
+
x, y, bw, bh = obj["bbox"]
|
| 101 |
+
return x, y, x + bw, y + bh
|
| 102 |
+
q = np.asarray(obj["corners"], float)
|
| 103 |
+
return (*q.min(0), *q.max(0))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def clip_box(box, w, h):
|
| 107 |
+
x0, y0, x1, y1 = box
|
| 108 |
+
return (min(max(x0, 0), w - 1), min(max(y0, 0), h - 1),
|
| 109 |
+
min(max(x1, 0), w - 1), min(max(y1, 0), h - 1))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def mask_box(obj, w, h):
|
| 113 |
+
x0, y0, x1, y1 = obj_box(obj)
|
| 114 |
+
px, py = (x1 - x0) * MASK_PAD, (y1 - y0) * MASK_PAD
|
| 115 |
+
return clip_box((x0 - px, y0 - py, x1 + px, y1 + py), w, h)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def keypoints(obj, order, w, h):
|
| 119 |
+
"""Clipped corners (4x2), visibility (4,) and clipped box. Box-only labels get invisible points."""
|
| 120 |
+
box = clip_box(obj_box(obj), w, h)
|
| 121 |
+
if "corners" not in obj:
|
| 122 |
+
return np.zeros((4, 2)), np.zeros(4, int), box
|
| 123 |
+
q = np.asarray(obj["corners"], float)[order]
|
| 124 |
+
inside = (q[:, 0] >= 0) & (q[:, 0] < w) & (q[:, 1] >= 0) & (q[:, 1] < h)
|
| 125 |
+
vis = np.where(inside, np.asarray(obj.get("visibility", [2, 2, 2, 2]), int)[order], 0)
|
| 126 |
+
return np.clip(q, 0, [w - 1, h - 1]), vis, box
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def yolo_pose_line(cls, obj, order, w, h):
|
| 130 |
+
pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
|
| 131 |
+
vals = [(x0 + x1) / 2 / w, (y0 + y1) / 2 / h, (x1 - x0) / w, (y1 - y0) / h]
|
| 132 |
+
for (x, y), v in zip(pts, vis):
|
| 133 |
+
vals += [x / w, y / h, int(v)]
|
| 134 |
+
return f"{cls} " + " ".join(f"{v:.6g}" for v in vals)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def sjtu_line(cls, obj, w, h):
|
| 138 |
+
q = np.asarray(obj["corners"], float) / [w, h]
|
| 139 |
+
return f"{cls} " + " ".join(f"{v:.6g}" for v in q.ravel())
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids):
|
| 143 |
+
if cls is None:
|
| 144 |
+
x0, y0, x1, y1 = mask_box(obj, w, h)
|
| 145 |
+
kps, nk = [0] * 12, 0
|
| 146 |
+
else:
|
| 147 |
+
pts, vis, (x0, y0, x1, y1) = keypoints(obj, order, w, h)
|
| 148 |
+
kps = [v for (x, y), s in zip(pts, vis) for v in (round(float(x), 2), round(float(y), 2), int(s))]
|
| 149 |
+
nk = int((vis > 0).sum())
|
| 150 |
+
fields = {k: obj[k] for k in ATTR_KEYS if k in obj}
|
| 151 |
+
side = {"red": 0, "blue": 100}.get(obj.get("color"))
|
| 152 |
+
if side is not None and obj.get("sticker") in ref_ids:
|
| 153 |
+
fields["ref_id"] = ref_ids[obj["sticker"]] + side
|
| 154 |
+
bw, bh = float(x1 - x0), float(y1 - y0)
|
| 155 |
+
return {
|
| 156 |
+
"id": ann_id, "image_id": img_id, "category_id": 1 if cls is None else cls + 1,
|
| 157 |
+
"iscrowd": int(cls is None), "num_keypoints": nk, "keypoints": kps,
|
| 158 |
+
"bbox": [round(float(x0), 2), round(float(y0), 2), round(bw, 2), round(bh, 2)],
|
| 159 |
+
"area": round(bw * bh, 2), "attributes": fields,
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main():
|
| 164 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 165 |
+
ap.add_argument("input")
|
| 166 |
+
ap.add_argument("output")
|
| 167 |
+
ap.add_argument("--format", choices=["yolo-pose", "coco", "sjtu"], default="yolo-pose")
|
| 168 |
+
ap.add_argument("--classes", choices=["sjtu", "color", "plate"], default="sjtu")
|
| 169 |
+
ap.add_argument("--order", choices=list(ORDERS), default="sjtu",
|
| 170 |
+
help="keypoint order for yolo-pose / coco (sjtu txt is always LT,LB,RB,RT)")
|
| 171 |
+
ap.add_argument("--split", default="", help="comma list, e.g. train,test (default all)")
|
| 172 |
+
ap.add_argument("--source", default="", help="comma list of sources (default all)")
|
| 173 |
+
ap.add_argument("--quality", type=int, default=95, help="JPEG quality for masked images")
|
| 174 |
+
args = ap.parse_args()
|
| 175 |
+
|
| 176 |
+
splits = set(filter(None, args.split.split(",")))
|
| 177 |
+
sources = set(filter(None, args.source.split(",")))
|
| 178 |
+
order = ORDERS[args.order]
|
| 179 |
+
ref_ids = {s["id"]: s["ref_id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
|
| 180 |
+
out = Path(args.output)
|
| 181 |
+
stats = {"images": 0, "labels": 0, "masked": 0}
|
| 182 |
+
seen_splits = set()
|
| 183 |
+
coco = {}
|
| 184 |
+
ann_id = 0
|
| 185 |
+
|
| 186 |
+
for split, key, jpg, label in iter_samples(args.input):
|
| 187 |
+
source = label["image"].get("source") or "nosource"
|
| 188 |
+
if (splits and split not in splits) or (sources and source not in sources):
|
| 189 |
+
continue
|
| 190 |
+
w, h = label["image"]["width"], label["image"]["height"]
|
| 191 |
+
name = f"{source}__{key.replace('/', '__')}"
|
| 192 |
+
img_dir = out / "images" / split
|
| 193 |
+
img_dir.mkdir(parents=True, exist_ok=True)
|
| 194 |
+
seen_splits.add(split)
|
| 195 |
+
stats["images"] += 1
|
| 196 |
+
|
| 197 |
+
# null means "not labelled": drop those keys so presence checks below stay simple
|
| 198 |
+
objs = [{k: v for k, v in o.items() if v is not None} for o in label.get("objects", [])]
|
| 199 |
+
objs = [o for o in objs if o.get("role", "positive") != "negative"]
|
| 200 |
+
classes = [class_id(o, args.classes) if o.get("role", "positive") == "positive" else None
|
| 201 |
+
for o in objs]
|
| 202 |
+
|
| 203 |
+
if args.format == "coco":
|
| 204 |
+
ds = coco.setdefault(split, {"images": [], "annotations": []})
|
| 205 |
+
img_id = len(ds["images"]) + 1
|
| 206 |
+
ds["images"].append({**label["image"], "id": img_id, "file_name": f"{split}/{name}.jpg"})
|
| 207 |
+
for obj, cls in zip(objs, classes):
|
| 208 |
+
ann_id += 1
|
| 209 |
+
ds["annotations"].append(coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids))
|
| 210 |
+
stats["labels" if cls is not None else "masked"] += 1
|
| 211 |
+
(img_dir / f"{name}.jpg").write_bytes(jpg)
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
lines, masks = [], []
|
| 215 |
+
for obj, cls in zip(objs, classes):
|
| 216 |
+
if cls is None or (args.format == "sjtu" and "corners" not in obj):
|
| 217 |
+
masks.append(mask_box(obj, w, h))
|
| 218 |
+
elif args.format == "yolo-pose":
|
| 219 |
+
lines.append(yolo_pose_line(cls, obj, order, w, h))
|
| 220 |
+
else:
|
| 221 |
+
lines.append(sjtu_line(cls, obj, w, h))
|
| 222 |
+
if masks:
|
| 223 |
+
im = Image.open(io.BytesIO(jpg)).convert("RGB")
|
| 224 |
+
draw = ImageDraw.Draw(im)
|
| 225 |
+
for box in masks:
|
| 226 |
+
draw.rectangle(box, fill=GREY)
|
| 227 |
+
im.save(img_dir / f"{name}.jpg", quality=args.quality)
|
| 228 |
+
else:
|
| 229 |
+
(img_dir / f"{name}.jpg").write_bytes(jpg)
|
| 230 |
+
lbl_dir = out / "labels" / split
|
| 231 |
+
lbl_dir.mkdir(parents=True, exist_ok=True)
|
| 232 |
+
(lbl_dir / f"{name}.txt").write_text("".join(l + "\n" for l in lines))
|
| 233 |
+
stats["labels"] += len(lines)
|
| 234 |
+
stats["masked"] += len(masks)
|
| 235 |
+
|
| 236 |
+
names = class_names(args.classes)
|
| 237 |
+
flip = [order.index(MIRROR[order[j]]) for j in range(4)]
|
| 238 |
+
if args.format == "coco":
|
| 239 |
+
kp_names = [["LT", "LB", "RB", "RT"][i] for i in order]
|
| 240 |
+
categories = [{"id": i + 1, "name": n, "keypoints": kp_names,
|
| 241 |
+
"skeleton": [[1, 2], [2, 3], [3, 4], [4, 1]]} for i, n in enumerate(names)]
|
| 242 |
+
(out / "annotations").mkdir(parents=True, exist_ok=True)
|
| 243 |
+
for split, ds in coco.items():
|
| 244 |
+
ds["categories"] = categories
|
| 245 |
+
ds["info"] = {"description": "rmcv/armor", "flip_idx": flip}
|
| 246 |
+
(out / "annotations" / f"{split}.json").write_text(json.dumps(ds, ensure_ascii=False), "utf-8")
|
| 247 |
+
elif args.format == "yolo-pose":
|
| 248 |
+
yaml = [f"path: {out.resolve().as_posix()}"]
|
| 249 |
+
yaml += [f"{'val' if s == 'test' else s}: images/{s}" for s in sorted(seen_splits)]
|
| 250 |
+
yaml += ["kpt_shape: [4, 3]", f"flip_idx: {flip}",
|
| 251 |
+
"# Horizontal flips mirror the digit; train with fliplr: 0.", "names:"]
|
| 252 |
+
yaml += [f" {i}: {n}" for i, n in enumerate(names)]
|
| 253 |
+
(out / "data.yaml").write_text("\n".join(yaml) + "\n")
|
| 254 |
+
|
| 255 |
+
print(json.dumps(stats))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
main()
|
tools/pack.py
CHANGED
|
@@ -1,122 +1,136 @@
|
|
| 1 |
-
"""Check rmcv/armor labels and pack <key>.jpg + <key>.json pairs into WebDataset tar shards.
|
| 2 |
-
|
| 3 |
-
Usage:
|
| 4 |
-
python pack.py <input_dir> <dataset_root> --source <source> --split train|test [--shard-mb 1024]
|
| 5 |
-
|
| 6 |
-
Writes <dataset_root>/data/<source>/<split>/<source>-<split>-00000.tar ... and prints a
|
| 7 |
-
summary. Every label is checked first; nothing is written if any label fails.
|
| 8 |
-
|
| 9 |
-
Requires Pillow.
|
| 10 |
-
"""
|
| 11 |
-
|
| 12 |
-
import argparse
|
| 13 |
-
import io
|
| 14 |
-
import json
|
| 15 |
-
import re
|
| 16 |
-
import sys
|
| 17 |
-
import tarfile
|
| 18 |
-
from pathlib import Path
|
| 19 |
-
|
| 20 |
-
from PIL import Image
|
| 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 |
-
if "
|
| 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 |
-
if
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Check rmcv/armor labels and pack <key>.jpg + <key>.json pairs into WebDataset tar shards.
|
| 2 |
+
|
| 3 |
+
Usage:
|
| 4 |
+
python pack.py <input_dir> <dataset_root> --source <source> --split train|test [--shard-mb 1024]
|
| 5 |
+
|
| 6 |
+
Writes <dataset_root>/data/<source>/<split>/<source>-<split>-00000.tar ... and prints a
|
| 7 |
+
summary. Every label is checked first; nothing is written if any label fails.
|
| 8 |
+
|
| 9 |
+
Requires Pillow.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import io
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import sys
|
| 17 |
+
import tarfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
from PIL import Image
|
| 21 |
+
|
| 22 |
+
IMAGE_KEYS = ["width", "height", "source", "sequence", "frame", "camera"]
|
| 23 |
+
OBJECT_KEYS = ["corners", "bbox", "color", "size", "sticker", "visibility", "flags",
|
| 24 |
+
"corner_def", "label_type", "role"]
|
| 25 |
+
ENUMS = {
|
| 26 |
+
"color": {"blue", "red", "gray", "purple"},
|
| 27 |
+
"size": {"small", "large"},
|
| 28 |
+
"corner_def": {"sjtu4", "unspecified"},
|
| 29 |
+
"label_type": {"human", "human_checked", "model"},
|
| 30 |
+
"role": {"positive", "ignore", "negative"},
|
| 31 |
+
}
|
| 32 |
+
FLAGS = {"truncated", "occluded", "motion_blur", "overexposed", "unlit"}
|
| 33 |
+
STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def check(label, jpg, stickers):
|
| 37 |
+
"""Return a list of problems for one image."""
|
| 38 |
+
errors = []
|
| 39 |
+
image = label.get("image", {})
|
| 40 |
+
if set(image) - set(IMAGE_KEYS):
|
| 41 |
+
errors.append(f"image: unknown keys {sorted(set(image) - set(IMAGE_KEYS))}")
|
| 42 |
+
try:
|
| 43 |
+
w, h = Image.open(io.BytesIO(jpg)).size
|
| 44 |
+
except Exception as e: # unreadable image
|
| 45 |
+
return [f"image: {e}"]
|
| 46 |
+
if (image.get("width"), image.get("height")) != (w, h):
|
| 47 |
+
errors.append(f"image size {image.get('width')}x{image.get('height')} != jpg {w}x{h}")
|
| 48 |
+
for i, obj in enumerate(label.get("objects", [])):
|
| 49 |
+
where = f"objects[{i}]"
|
| 50 |
+
if set(obj) - set(OBJECT_KEYS):
|
| 51 |
+
errors.append(f"{where}: unknown keys {sorted(set(obj) - set(OBJECT_KEYS))}")
|
| 52 |
+
obj = {k: v for k, v in obj.items() if v is not None}
|
| 53 |
+
if "corners" not in obj and "bbox" not in obj:
|
| 54 |
+
errors.append(f"{where}: needs corners or bbox")
|
| 55 |
+
if "corners" in obj:
|
| 56 |
+
q = obj["corners"]
|
| 57 |
+
if len(q) != 4 or any(len(p) != 2 for p in q):
|
| 58 |
+
errors.append(f"{where}: corners must be 4 [x, y] points")
|
| 59 |
+
else:
|
| 60 |
+
area = sum(q[k][0] * q[(k + 1) % 4][1] - q[k][1] * q[(k + 1) % 4][0] for k in range(4))
|
| 61 |
+
if area >= 0:
|
| 62 |
+
errors.append(f"{where}: corners not LT, LB, RB, RT counter-clockwise")
|
| 63 |
+
if "bbox" in obj and (len(obj["bbox"]) != 4 or obj["bbox"][2] <= 0 or obj["bbox"][3] <= 0):
|
| 64 |
+
errors.append(f"{where}: bbox must be [x, y, w, h] with w, h > 0")
|
| 65 |
+
for key, allowed in ENUMS.items():
|
| 66 |
+
if key in obj and obj[key] not in allowed:
|
| 67 |
+
errors.append(f"{where}: {key}={obj[key]!r}")
|
| 68 |
+
if "sticker" in obj and obj["sticker"] not in stickers:
|
| 69 |
+
errors.append(f"{where}: sticker={obj['sticker']!r} not in stickers.json")
|
| 70 |
+
if "visibility" in obj and (len(obj["visibility"]) != 4 or set(obj["visibility"]) - {0, 1, 2}):
|
| 71 |
+
errors.append(f"{where}: visibility must be 4 values of 0/1/2")
|
| 72 |
+
if set(obj.get("flags", [])) - FLAGS:
|
| 73 |
+
errors.append(f"{where}: unknown flags {sorted(set(obj['flags']) - FLAGS)}")
|
| 74 |
+
return errors
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def normalize(label):
|
| 78 |
+
"""Write every image / object with the same keys (missing -> null) so readers see one schema."""
|
| 79 |
+
return {"image": {k: label["image"].get(k) for k in IMAGE_KEYS},
|
| 80 |
+
"objects": [{k: o.get(k) for k in OBJECT_KEYS} for o in label.get("objects", [])]}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 85 |
+
ap.add_argument("input_dir")
|
| 86 |
+
ap.add_argument("dataset_root")
|
| 87 |
+
ap.add_argument("--source", required=True)
|
| 88 |
+
ap.add_argument("--split", required=True, choices=["train", "test"])
|
| 89 |
+
ap.add_argument("--shard-mb", type=int, default=1024)
|
| 90 |
+
args = ap.parse_args()
|
| 91 |
+
|
| 92 |
+
if not re.fullmatch(r"[a-z0-9_]+", args.source):
|
| 93 |
+
sys.exit("source must use lowercase letters, digits and underscores")
|
| 94 |
+
stickers = {s["id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
|
| 95 |
+
|
| 96 |
+
pairs, problems = [], []
|
| 97 |
+
for json_path in sorted(Path(args.input_dir).rglob("*.json")):
|
| 98 |
+
jpg_path = json_path.with_suffix(".jpg")
|
| 99 |
+
if not jpg_path.exists():
|
| 100 |
+
continue
|
| 101 |
+
label = json.loads(json_path.read_text("utf-8"))
|
| 102 |
+
label.setdefault("image", {})["source"] = args.source
|
| 103 |
+
jpg = jpg_path.read_bytes()
|
| 104 |
+
problems += [f"{json_path.name}: {e}" for e in check(label, jpg, stickers)]
|
| 105 |
+
pairs.append((json_path.stem, jpg, label))
|
| 106 |
+
if problems:
|
| 107 |
+
print("\n".join(problems[:50]))
|
| 108 |
+
sys.exit(f"{len(problems)} problems, nothing written")
|
| 109 |
+
if not pairs:
|
| 110 |
+
sys.exit("no <key>.jpg + <key>.json pairs found")
|
| 111 |
+
|
| 112 |
+
out_dir = Path(args.dataset_root) / "data" / args.source / args.split
|
| 113 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
limit = args.shard_mb * 1024 * 1024
|
| 115 |
+
shard, size, tar, counts = 0, 0, None, {"images": 0, "objects": 0, "shards": 0}
|
| 116 |
+
for key, jpg, label in pairs:
|
| 117 |
+
data = json.dumps(normalize(label), ensure_ascii=False).encode("utf-8")
|
| 118 |
+
if tar is None or size + len(jpg) + len(data) > limit:
|
| 119 |
+
if tar:
|
| 120 |
+
tar.close()
|
| 121 |
+
tar = tarfile.open(out_dir / f"{args.source}-{args.split}-{shard:05d}.tar", "w")
|
| 122 |
+
shard, size = shard + 1, 0
|
| 123 |
+
counts["shards"] += 1
|
| 124 |
+
for ext, payload in (("jpg", jpg), ("json", data)):
|
| 125 |
+
info = tarfile.TarInfo(f"{key}.{ext}")
|
| 126 |
+
info.size = len(payload)
|
| 127 |
+
tar.addfile(info, io.BytesIO(payload))
|
| 128 |
+
size += len(jpg) + len(data) + 2048
|
| 129 |
+
counts["images"] += 1
|
| 130 |
+
counts["objects"] += len(label.get("objects", []))
|
| 131 |
+
tar.close()
|
| 132 |
+
print(json.dumps({"out": str(out_dir), **counts}))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
main()
|