SteppeDu lconlcong commited on
Commit
f6bbae3
·
0 Parent(s):

Duplicate from rmcv/armor

Browse files

Co-authored-by: XRobot <lconlcong@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.avro filter=lfs diff=lfs merge=lfs -text
4
+ *.bin filter=lfs diff=lfs merge=lfs -text
5
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
6
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
7
+ *.ftz filter=lfs diff=lfs merge=lfs -text
8
+ *.gz filter=lfs diff=lfs merge=lfs -text
9
+ *.h5 filter=lfs diff=lfs merge=lfs -text
10
+ *.joblib filter=lfs diff=lfs merge=lfs -text
11
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
13
+ *.mds filter=lfs diff=lfs merge=lfs -text
14
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
+ *.model filter=lfs diff=lfs merge=lfs -text
16
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
17
+ *.npy filter=lfs diff=lfs merge=lfs -text
18
+ *.npz filter=lfs diff=lfs merge=lfs -text
19
+ *.onnx filter=lfs diff=lfs merge=lfs -text
20
+ *.ot filter=lfs diff=lfs merge=lfs -text
21
+ *.parquet filter=lfs diff=lfs merge=lfs -text
22
+ *.pb filter=lfs diff=lfs merge=lfs -text
23
+ *.pickle filter=lfs diff=lfs merge=lfs -text
24
+ *.pkl filter=lfs diff=lfs merge=lfs -text
25
+ *.pt filter=lfs diff=lfs merge=lfs -text
26
+ *.pth filter=lfs diff=lfs merge=lfs -text
27
+ *.rar filter=lfs diff=lfs merge=lfs -text
28
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
29
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
31
+ *.tar filter=lfs diff=lfs merge=lfs -text
32
+ *.tflite filter=lfs diff=lfs merge=lfs -text
33
+ *.tgz filter=lfs diff=lfs merge=lfs -text
34
+ *.wasm filter=lfs diff=lfs merge=lfs -text
35
+ *.xz filter=lfs diff=lfs merge=lfs -text
36
+ *.zip filter=lfs diff=lfs merge=lfs -text
37
+ *.zst filter=lfs diff=lfs merge=lfs -text
38
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
39
+ # Audio files - uncompressed
40
+ *.pcm filter=lfs diff=lfs merge=lfs -text
41
+ *.sam filter=lfs diff=lfs merge=lfs -text
42
+ *.raw filter=lfs diff=lfs merge=lfs -text
43
+ # Audio files - compressed
44
+ *.aac filter=lfs diff=lfs merge=lfs -text
45
+ *.flac filter=lfs diff=lfs merge=lfs -text
46
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
47
+ *.ogg filter=lfs diff=lfs merge=lfs -text
48
+ *.wav filter=lfs diff=lfs merge=lfs -text
49
+ # Image files - uncompressed
50
+ *.bmp filter=lfs diff=lfs merge=lfs -text
51
+ *.gif filter=lfs diff=lfs merge=lfs -text
52
+ *.png filter=lfs diff=lfs merge=lfs -text
53
+ *.tiff filter=lfs diff=lfs merge=lfs -text
54
+ # Image files - compressed
55
+ *.jpg filter=lfs diff=lfs merge=lfs -text
56
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
57
+ *.webp filter=lfs diff=lfs merge=lfs -text
58
+ # Video files - compressed
59
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
60
+ *.webm filter=lfs diff=lfs merge=lfs -text
LICENSE.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 授权
2
+
3
+ ## 数据
4
+
5
+ `data/<source>/` 下的图像与标签按来源分别授权,以 `sources.csv` 中该来源的 `license` 一列为准。使用某个来源的数据时请遵守其授权,并注明 `team` 与 `origin`。
6
+
7
+ ## 工具与文档
8
+
9
+ `tools/`、`stickers.json` 及本仓库的说明文档采用 MIT 许可证:
10
+
11
+ ```
12
+ MIT License
13
+
14
+ Copyright (c) 2026 rmcv contributors
15
+
16
+ Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ of this software and associated documentation files (the "Software"), to deal
18
+ in the Software without restriction, including without limitation the rights
19
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ copies of the Software, and to permit persons to whom the Software is
21
+ furnished to do so, subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be included in all
24
+ copies or substantial portions of the Software.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
+ SOFTWARE.
33
+ ```
README.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: RoboMaster Armor Plates
3
+ license: other
4
+ license_name: per-source
5
+ license_link: LICENSE.md
6
+ task_categories:
7
+ - object-detection
8
+ - keypoint-detection
9
+ tags:
10
+ - robomaster
11
+ - armor-plate
12
+ - webdataset
13
+ configs:
14
+ - config_name: default
15
+ data_files:
16
+ - split: train
17
+ path: "data/*/train/*.tar"
18
+ - config_name: qdu_damo
19
+ data_files:
20
+ - split: train
21
+ path: "data/qdu_damo/train/*.tar"
22
+ - config_name: qdu_gimbal_0507
23
+ data_files:
24
+ - split: train
25
+ path: "data/qdu_gimbal_0507/train/*.tar"
26
+ - config_name: qdu_gimbal_0509
27
+ data_files:
28
+ - split: train
29
+ path: "data/qdu_gimbal_0509/train/*.tar"
30
+ - config_name: mixed_armor
31
+ data_files:
32
+ - split: train
33
+ path: "data/mixed_armor/train/*.tar"
34
+ ---
35
+
36
+ # RoboMaster 装甲板数据集
37
+
38
+ 多支队伍共同维护的装甲板数据集。每块装甲板给出四个角点或检测框,以及颜色、大小和贴纸图案,有哪项给哪项。
39
+
40
+ ## 1. 文件
41
+
42
+ ```
43
+ data/<source>/<split>/<source>-<split>-00000.tar 图像和标签
44
+ data/<source>/cameras.json 相机内参(可选)
45
+ sources.csv 来源登记
46
+ stickers.json 贴纸图案登记
47
+ tools/pack.py 检查标签并打包
48
+ tools/export.py 导出为训练格式
49
+ ```
50
+
51
+ - `<source>`:来源编号,小写字母、数字和下划线,如 `qdu_infantry_2026`。
52
+ - `<split>`:`train` 或 `test`。同一段视频或同一个采集序列只放在一个 split 中。
53
+ - tar 分片每个 0.5–2 GB,内部成对存放 `<key>.jpg` 和 `<key>.json`(WebDataset 格式)。
54
+
55
+ ## 2. 标签
56
+
57
+ 每张图一个 JSON:
58
+
59
+ ```json
60
+ {
61
+ "image": {"width": 1440, "height": 1080, "source": "qdu_infantry_2026", "sequence": "match03", "camera": "cam0"},
62
+ "objects": [
63
+ {
64
+ "corners": [[612.3, 401.8], [610.9, 452.6], [741.2, 455.0], [742.8, 404.1]],
65
+ "color": "blue",
66
+ "size": "small",
67
+ "sticker": "3"
68
+ }
69
+ ]
70
+ }
71
+ ```
72
+
73
+ `corners` 和 `bbox` 至少有一个,其余字段有就填,没有就省略或写 `null`。缺失的字段在训练时只是该项不计损失,不影响其他字段。`tools/pack.py` 打包时会把每个对象补全为同一组字段,缺失的写成 `null`。
74
+
75
+ | 字段 | 取值 |
76
+ |---|---|
77
+ | `corners` | 四个角点的像素坐标,顺序见第 3 节 |
78
+ | `bbox` | `[x, y, w, h]`,只有框没有角点时填 |
79
+ | `color` | `blue`、`red`、`gray`(灭灯)、`purple` |
80
+ | `size` | `small`、`large` |
81
+ | `sticker` | 贴纸图案:`sentry`、`1`–`5`、`outpost`、`base` |
82
+ | `visibility` | 每个角点 0 不可见、1 被遮挡但可推断、2 可见;省略为全部可见 |
83
+ | `flags` | `truncated`、`occluded`、`motion_blur`、`overexposed`、`unlit` |
84
+ | `corner_def` | `sjtu4`(上交格式,默认)或 `unspecified`(不确定) |
85
+ | `label_type` | `human` 人工标注、`human_checked` 模型标注后人工检查、`model` 模型标注 |
86
+ | `role` | `positive`(默认)、`ignore`(不确定,训练时不计损失)、`negative`(确认不是装甲板) |
87
+ | `image.sequence` | 视频或采集序列编号 |
88
+ | `image.camera` | 对应 `cameras.json` 中的相机 |
89
+
90
+ 没有装甲板的图也可以上传,`objects` 留空,作为负样本。
91
+
92
+ `sticker` 记录贴纸上印的图案,不记录是哪台机器人。新赛季出现新图案时在 `stickers.json` 末尾追加一行。`stickers.json` 同时给出各图案对应的官方机器人 ID(《RMU 2026 通信协议》,红方 1–5、哨兵 7、基地 10、前哨站 11,蓝方加 100),只作对照。
93
+
94
+ ## 3. 角点
95
+
96
+ 角点采用上交 LabelRoboMaster 的定义,顺序为 LT, LB, RB, RT:
97
+
98
+ - 正对贴纸、图案正立时,左手边的灯条为左灯条。LT、LB 是左灯条的上端、下端,RB、RT 是右灯条的下端、上端。
99
+ - 上下左右按装甲板本身判定,不按图像坐标排序;装甲板倾斜很大时也一样。
100
+ - 在图像中四点依次为逆时针。顺序反了(或是镜像)的标注在导出时会被当作无效。
101
+ - 被图像边缘截断的角点,按装甲板形状推出图外的位置,`visibility` 记 0。
102
+
103
+ ## 4. 相机内参
104
+
105
+ 有标定的来源在 `data/<source>/cameras.json` 中给出内参,可用于 PnP 测距评测:
106
+
107
+ ```json
108
+ {"cam0": {"width": 1440, "height": 1080, "fx": 1800.0, "fy": 1800.0, "cx": 720.0, "cy": 540.0, "dist": [0, 0, 0, 0, 0]}}
109
+ ```
110
+
111
+ `dist` 为 OpenCV 畸变系数 `[k1, k2, p1, p2, k3]`。内参对应图像的实际分辨率,缩放、裁剪、binning 后要相应换算。
112
+
113
+ ## 5. 导出
114
+
115
+ ```bash
116
+ python tools/export.py <armor/data> <输出目录> # YOLO pose
117
+ python tools/export.py <armor/data> <输出目录> --format coco # COCO 关键点
118
+ python tools/export.py <armor/data> <输出目录> --format sjtu # 上交 txt
119
+ ```
120
+
121
+ - `--classes`:`sjtu`(默认,与上交 36 类编号一致���、`color`(只分红蓝)、`plate`(单类)。
122
+ - `--order tongji`:关键点按 TL, TR, BR, BL 输出。
123
+ - `ignore` 区域和无法归类的装甲板:YOLO pose 和上交 txt 中涂灰,COCO 中写成 `iscrowd: 1`;`negative` 作为背景。
124
+ - 训练时不要开水平翻转,翻转后数字是镜像的。
125
+
126
+ 依赖 numpy 和 Pillow。
127
+
128
+ ## 6. 贡献
129
+
130
+ 1. 只上传自己队拍摄、自己标注的数据;转载需写明出处并确认原授权允许再分发。
131
+ 2. 把 `<key>.jpg` 和 `<key>.json` 放在同一个文件夹,用 `tools/pack.py` 检查并打包(有任何一条标签不合格都不会写出),再在 `sources.csv` 中登记一行:
132
+
133
+ ```bash
134
+ python tools/pack.py <文件夹> <仓库根目录> --source qdu_damo --split train
135
+ ```
136
+
137
+
138
+ | 列 | 内容 |
139
+ |---|---|
140
+ | `source` | 来源编号 |
141
+ | `team` | 队伍 |
142
+ | `year` | 采集年份 |
143
+ | `camera` | 相机、分辨率、帧率 |
144
+ | `scene` | 场地或赛事 |
145
+ | `images`、`objects` | 图像数、装甲板数 |
146
+ | `label_tool` | 标注工具 |
147
+ | `license` | 授权,如 `CC-BY-4.0` |
148
+ | `origin` | 自采,或原始链接 |
149
+
150
+ 3. 有 write 权限的维护者直接上传,其他人发 Pull Request。
151
+ 4. 每次合并新来源后打版本标签(`v1`、`v2` …),训练时固定版本:
152
+
153
+ ```python
154
+ from datasets import load_dataset
155
+ ds = load_dataset("rmcv/armor", revision="v1", split="train", streaming=True)
156
+ ```
157
+
158
+ ## 7. 授权
159
+
160
+ 数据按来源分别授权,以 `sources.csv` 为准;工具和文档采用 MIT,见 `LICENSE.md`。
161
+
162
+ ## 8. mixed_armor 来源说明
163
+
164
+ `mixed_armor`(5635 图 / 7634 目标,2021–2025,19 种分辨率)是**多来源混合数据**,原始出处已不可考,
165
+ 因此无法逐一署名,也无法逐一确认上游授权。我们完成的工作是标注整理:
166
+
167
+ - 用 4 个独立模型的角点共识替换了偏差 > 5px 的标注,随后**逐张人工复核**(288 帧,改动 402 个标签文件);
168
+ 复核后与 4 模型共识的角点偏差 p50 从 7.15px 降到 1.79px。
169
+ - 去除了字节级重复与近重复画面(RMSE ≤ 3),并排除了复核者标记为不可用的 2 帧。
170
+
171
+ **授权范围说明**:`sources.csv` 中本来源的 `CC-BY-4.0` **仅覆盖我们完成的标注部分**;
172
+ 图像原始版权归属无法考证,若权利人认为此处使用不当,请联系我们删除该来源。
173
+ 使用本来源时请一并注明 `origin` 一列的说明。
data/mixed_armor/train/mixed_armor-train-00000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b9146ea6f347191d10bb1a2db5c75f0623e7fcc6298fb705e1aa9965925f7e88
3
+ size 976793600
data/qdu_damo/cameras.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cs016_8mm": {
3
+ "width": 1440, "height": 1080,
4
+ "fx": 2328.6857198980888, "fy": 2328.6701077899961,
5
+ "cx": 733.35646250924742, "cy": 540.61872869227727,
6
+ "dist": [-0.091821039187099038, 0.46399073468302049, 0.0026098786426372819, 0.0009819586010405485, -0.47512788503104569]
7
+ }
8
+ }
data/qdu_damo/train/qdu_damo-train-00000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52c94bec06c3eee80897bae5477f102317fe8655c569bc3296f8dc7864ab951d
3
+ size 215388160
data/qdu_gimbal_0507/cameras.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cs016_8mm_2x2": {
3
+ "width": 720, "height": 540,
4
+ "fx": 1164.3428599490444, "fy": 1164.3350538949981,
5
+ "cx": 366.67823125462371, "cy": 270.30936434613864,
6
+ "dist": [-0.091821039187099038, 0.46399073468302049, 0.0026098786426372819, 0.0009819586010405485, -0.47512788503104569]
7
+ }
8
+ }
data/qdu_gimbal_0507/train/qdu_gimbal_0507-train-00000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5c699734af383a63bde07549aecf3b1f01ee83f7bd977b767756757d1f7414ce
3
+ size 144414720
data/qdu_gimbal_0509/cameras.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cs016_8mm_2x2": {
3
+ "width": 720, "height": 540,
4
+ "fx": 1164.3428599490444, "fy": 1164.3350538949981,
5
+ "cx": 366.67823125462371, "cy": 270.30936434613864,
6
+ "dist": [-0.091821039187099038, 0.46399073468302049, 0.0026098786426372819, 0.0009819586010405485, -0.47512788503104569]
7
+ }
8
+ }
data/qdu_gimbal_0509/train/qdu_gimbal_0509-train-00000.tar ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3949562cea031db5d5da955a6c97fb8e890867976180d881ebb73d48c10d74f4
3
+ size 261437440
sources.csv ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ source,team,year,camera,scene,images,objects,label_tool,license,origin
2
+ qdu_damo,青岛大学,2026,"海康 MV-CS016 + 8 mm, 1440x1080, 100 fps",实验室,404,539,模型自动标注,CC-BY-4.0,自采
3
+ qdu_gimbal_0507,青岛大学,2026,"海康 MV-CS016 + 8 mm, 720x540 (2x2), 100 fps, 每 20 帧取 1 帧",实验室,1434,2580,模型自动标注,CC-BY-4.0,自采
4
+ qdu_gimbal_0509,青岛大学,2026,"海康 MV-CS016 + 8 mm, 720x540 (2x2), 约 20 fps",实验室,1650,4998,模型自动标注,CC-BY-4.0,自采
5
+ mixed_armor,ARTINX,2021-2025,多种相机(19 种分辨率:1280x768 / 1280x1024 / 1440x1080 / 640x480 等),多来源混合场景(实验室 / 赛场 / 公开视频),5635,7634,4 模型共识 + 人工逐张复核,CC-BY-4.0,多来源聚合;原始出处已不可考,仅作研究用途,详见 README 第 8 节
stickers.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "note": "Append-only. ref_id = robot ID in the RMU 2026 communication protocol (red; blue = ref_id + 100).",
3
+ "stickers": [
4
+ {"id": "sentry", "name": "哨兵", "ref_id": 7},
5
+ {"id": "1", "name": "1 号", "ref_id": 1},
6
+ {"id": "2", "name": "2 号", "ref_id": 2},
7
+ {"id": "3", "name": "3 号", "ref_id": 3},
8
+ {"id": "4", "name": "4 号", "ref_id": 4},
9
+ {"id": "5", "name": "5 号", "ref_id": 5},
10
+ {"id": "outpost", "name": "前哨站", "ref_id": 11},
11
+ {"id": "base", "name": "基地", "ref_id": 10}
12
+ ]
13
+ }
tools/export.py ADDED
@@ -0,0 +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") 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 ADDED
@@ -0,0 +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
+ 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()