lconlcong commited on
Commit
fd8b7e3
·
verified ·
1 Parent(s): f353ea5

Add QDU recordings: qdu_damo, qdu_gimbal_0507, qdu_gimbal_0509; add pack.py

Browse files
README.md CHANGED
@@ -1,140 +1,146 @@
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
- - split: test
19
- path: "data/*/test/*.tar"
20
- ---
21
-
22
- # RoboMaster 装甲板数据集
23
-
24
- 多支队伍共同维护的装甲板数据集。每块装甲板给出四个角点或检测框,以及颜色、大小和贴纸图案,有哪项给哪项。
25
-
26
- ## 1. 文件
27
-
28
- ```
29
- data/<source>/<split>/<source>-<split>-00000.tar 图像和标签
30
- data/<source>/cameras.json 相机内参(可选)
31
- sources.csv 来源登记
32
- stickers.json 贴纸图案登记
33
- tools/export.py 导出为训练格式
34
- ```
35
-
36
- - `<source>`:来源编号,小写字母、数字和下划线,如 `qdu_infantry_2026`。
37
- - `<split>`:`train` 或 `test`。同一段视频或同一个采集序列只放在一个 split 中。
38
- - tar 分片每个 0.5–2 GB,内部成对存放 `<key>.jpg` 和 `<key>.json`(WebDataset 格式)。
39
-
40
- ## 2. 标签
41
-
42
- 每张图一个 JSON:
43
-
44
- ```json
45
- {
46
- "image": {"width": 1440, "height": 1080, "source": "qdu_infantry_2026", "sequence": "match03", "camera": "cam0"},
47
- "objects": [
48
- {
49
- "corners": [[612.3, 401.8], [610.9, 452.6], [741.2, 455.0], [742.8, 404.1]],
50
- "color": "blue",
51
- "size": "small",
52
- "sticker": "3"
53
- }
54
- ]
55
- }
56
- ```
57
-
58
- `corners` 和 `bbox` 至少有一个,其余字段有就填,没有就省略。缺失的字段在训练时只是该项不计损失,不影响其他字段。
59
-
60
- | 字段 | 取值 |
61
- |---|---|
62
- | `corners` | 四个角点的像素坐标,顺序见第 3 节 |
63
- | `bbox` | `[x, y, w, h]`,只有框没有角点时填 |
64
- | `color` | `blue`、`red`、`gray`(灭灯)、`purple` |
65
- | `size` | `small`、`large` |
66
- | `sticker` | 贴纸图案:`sentry`、`1`–`5`、`outpost`、`base` |
67
- | `visibility` | 每个角点 0 不可见、1 被遮挡但可推断、2 可见;省略为全部可见 |
68
- | `flags` | `truncated`、`occluded`、`motion_blur`、`overexposed`、`unlit` |
69
- | `corner_def` | `sjtu4`(上交格式,默认)或 `unspecified`(不确定) |
70
- | `label_type` | `human` 人工标注、`human_checked` 模型标注后人工检查、`model` 模型标注 |
71
- | `role` | `positive`(默认)、`ignore`(不确定,训练时不计损失)、`negative`(确认不是装甲板) |
72
- | `image.sequence` | 视频或采集序列编号 |
73
- | `image.camera` | 对应 `cameras.json` 中的相机 |
74
-
75
- 没有装甲板的图也可以上传,`objects` 留空,作为负样本。
76
-
77
- `sticker` 记录贴纸上印的图案,不记录是哪台机器人。新赛季出现新图案时在 `stickers.json` 末尾追加一行。`stickers.json` 同时给出各图案对应的官方机器人 ID(《RMU 2026 通信协议》,红方 1–5、哨兵 7、基地 10、前哨站 11,蓝方加 100),只作对照。
78
-
79
- ## 3. 角点
80
-
81
- 角点采用上交 LabelRoboMaster 的定义,顺序为 LT, LB, RB, RT:
82
-
83
- - 正对贴纸、图案正立时,左手边的灯条为左灯条。LT、LB 是左灯条的上端、下端,RB、RT 是右灯条的下端、上端。
84
- - 上下左右按装甲板本身判定,不按图像坐标排序;装甲板倾斜很大时也一样。
85
- - 在图像中四点依次为逆时针。顺序反了(或是镜像)的标注在导出时会被当作无效。
86
- - 被图像边缘截断的角点,按装甲板形状推出图外的位置,`visibility` 记 0。
87
-
88
- ## 4. 相机内参
89
-
90
- 有标定的来源在 `data/<source>/cameras.json` 中给出内参,可用于 PnP 测距评测:
91
-
92
- ```json
93
- {"cam0": {"width": 1440, "height": 1080, "fx": 1800.0, "fy": 1800.0, "cx": 720.0, "cy": 540.0, "dist": [0, 0, 0, 0, 0]}}
94
- ```
95
-
96
- `dist` 为 OpenCV 畸变系数 `[k1, k2, p1, p2, k3]`。内参对应图像的实际分辨率,缩放、裁剪、binning 后要相应换算。
97
-
98
- ## 5. 导出
99
-
100
- ```bash
101
- python tools/export.py <armor/data> <输出目录> # YOLO pose
102
- python tools/export.py <armor/data> <输出目录> --format coco # COCO 关键点
103
- python tools/export.py <armor/data> <输出目录> --format sjtu # 上交 txt
104
- ```
105
-
106
- - `--classes`:`sjtu`(默认,与上交 36 类编号一致)、`color`(只分红蓝)、`plate`(单类)。
107
- - `--order tongji`:关键点按 TL, TR, BR, BL 输出。
108
- - `ignore` 区域和无法归类的装甲板:YOLO pose 和上交 txt 中涂灰,COCO 中写成 `iscrowd: 1`;`negative` 作为背景。
109
- - 训练时不要开水平翻转,翻转后数字是镜像的。
110
-
111
- 依赖 numpy 和 Pillow。
112
-
113
- ## 6. 贡献
114
-
115
- 1. 只上传自己队拍摄、自己标注的数据;转载需写明出处并确认原授权允许再分发。
116
- 2. 按第 1、2 节打包,在 `sources.csv` 中登记一行:
117
-
118
- | 列 | 内容 |
119
- |---|---|
120
- | `source` | 来源编号 |
121
- | `team` | 队伍 |
122
- | `year` | 采集年份 |
123
- | `camera` | 相机、分辨率、帧率 |
124
- | `scene` | 场地或赛事 |
125
- | `images`、`objects` | 图像数、装甲板数 |
126
- | `label_tool` | 标注工具 |
127
- | `license` | 授权,如 `CC-BY-4.0` |
128
- | `origin` | 自采,或原始链接 |
129
-
130
- 3. 有 write 权限的维护者直接上传,其他人发 Pull Request。
131
- 4. 每次合并新来源后打版本标签(`v1`、`v2` …),训练时固定版本:
132
-
133
- ```python
134
- from datasets import load_dataset
135
- ds = load_dataset("rmcv/armor", revision="v1", split="train", streaming=True)
136
- ```
137
-
138
- ## 7. 授权
139
-
140
- 数据按来源分别授权,以 `sources.csv` 为准;工具和文档采用 MIT,见 `LICENSE.md`。
 
 
 
 
 
 
 
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
+ - split: test
19
+ path: "data/*/test/*.tar"
20
+ ---
21
+
22
+ # RoboMaster 装甲板数据集
23
+
24
+ 多支队伍共同维护的装甲板数据集。每块装甲板给出四个角点或检测框,以及颜色、大小和贴纸图案,有哪项给哪项。
25
+
26
+ ## 1. 文件
27
+
28
+ ```
29
+ data/<source>/<split>/<source>-<split>-00000.tar 图像和标签
30
+ data/<source>/cameras.json 相机内参(可选)
31
+ sources.csv 来源登记
32
+ stickers.json 贴纸图案登记
33
+ tools/pack.py 检查标签并打包
34
+ tools/export.py 导出为训练格式
35
+ ```
36
+
37
+ - `<source>`:来源编号,小写字母、数字和下划线,如 `qdu_infantry_2026`。
38
+ - `<split>`:`train` 或 `test`。同一段视频或同一个采集序列只放在一个 split 中。
39
+ - tar 分片每个 0.5–2 GB,内部成对存放 `<key>.jpg` 和 `<key>.json`(WebDataset 格式)。
40
+
41
+ ## 2. 标签
42
+
43
+ 每张图一个 JSON:
44
+
45
+ ```json
46
+ {
47
+ "image": {"width": 1440, "height": 1080, "source": "qdu_infantry_2026", "sequence": "match03", "camera": "cam0"},
48
+ "objects": [
49
+ {
50
+ "corners": [[612.3, 401.8], [610.9, 452.6], [741.2, 455.0], [742.8, 404.1]],
51
+ "color": "blue",
52
+ "size": "small",
53
+ "sticker": "3"
54
+ }
55
+ ]
56
+ }
57
+ ```
58
+
59
+ `corners` 和 `bbox` 至少有一个,其余字段有就填,没有就省略。缺失的字段在训练时只是该项不计损失,不影响其他字段。
60
+
61
+ | 字段 | 取值 |
62
+ |---|---|
63
+ | `corners` | 四个角点的像素坐标,顺序见第 3 节 |
64
+ | `bbox` | `[x, y, w, h]`,只有框没有角点时填 |
65
+ | `color` | `blue`、`red`、`gray`(灭灯)、`purple` |
66
+ | `size` | `small`、`large` |
67
+ | `sticker` | 贴纸图案:`sentry`、`1`–`5`、`outpost`、`base` |
68
+ | `visibility` | 每个角点 0 不可见、1 被遮挡但可推断、2 可见;省略为全部可见 |
69
+ | `flags` | `truncated`、`occluded`、`motion_blur`、`overexposed`、`unlit` |
70
+ | `corner_def` | `sjtu4`(上交格式,默认)或 `unspecified`(不确定) |
71
+ | `label_type` | `human` 人工标注、`human_checked` 模型标注后人工检查、`model` 模型标注 |
72
+ | `role` | `positive`(默认)、`ignore`(不确定,训练时不计损失)、`negative`(确认不是装甲板) |
73
+ | `image.sequence` | 视频或采集序列编号 |
74
+ | `image.camera` | 对应 `cameras.json` 中的相机 |
75
+
76
+ 没有装甲板的图也可以上传,`objects` 留空,作为负样本。
77
+
78
+ `sticker` 记录贴纸上印的图案,不记录是哪台机器人。新赛季出现新图案时在 `stickers.json` 末尾追加一行。`stickers.json` 同时给出各图案对应的官方机器人 ID(《RMU 2026 通信协议》,红方 1–5、哨兵 7、基地 10、前哨站 11,蓝方加 100),只作对照。
79
+
80
+ ## 3. 角点
81
+
82
+ 角点采用上交 LabelRoboMaster 的定义,顺序为 LT, LB, RB, RT:
83
+
84
+ - 正对贴纸、图案正立时,左手边的灯条为左灯条。LT、LB 是左灯条的上端、下端,RB、RT 是右灯条的下端、上端。
85
+ - 上下左右按装甲板本身判定,不按图像坐标排序;装甲板倾斜很大时也一样。
86
+ - 在图像中四点依次为逆时针。顺序反了(或是镜像)的标注在导出时会被当作无效。
87
+ - 被图像边缘截断的角点,按装甲板形状推出图外的位置,`visibility` 记 0。
88
+
89
+ ## 4. 相机内参
90
+
91
+ 有标定的来源在 `data/<source>/cameras.json` 中给出内参,可用于 PnP 测距评测:
92
+
93
+ ```json
94
+ {"cam0": {"width": 1440, "height": 1080, "fx": 1800.0, "fy": 1800.0, "cx": 720.0, "cy": 540.0, "dist": [0, 0, 0, 0, 0]}}
95
+ ```
96
+
97
+ `dist` 为 OpenCV 畸变系数 `[k1, k2, p1, p2, k3]`。内参对应图像的实际分辨率,缩放、裁剪、binning 后要相应换算。
98
+
99
+ ## 5. 导出
100
+
101
+ ```bash
102
+ python tools/export.py <armor/data> <输出目录> # YOLO pose
103
+ python tools/export.py <armor/data> <输出目录> --format coco # COCO 关键点
104
+ python tools/export.py <armor/data> <输出目录> --format sjtu # 上交 txt
105
+ ```
106
+
107
+ - `--classes`:`sjtu`(默认,与上交 36 类编号一致)、`color`(只分红蓝)、`plate`(单类)。
108
+ - `--order tongji`:关键点按 TL, TR, BR, BL 输出。
109
+ - `ignore` 区域和无法归类的装甲板:YOLO pose 和上交 txt 中涂灰,COCO 中写成 `iscrowd: 1`;`negative` 作为背景。
110
+ - 训练时不要开水平翻转,翻转后数字是镜像的。
111
+
112
+ 依赖 numpy 和 Pillow。
113
+
114
+ ## 6. 贡献
115
+
116
+ 1. 只上传自己队拍摄、自己标注的数据;转载需写明出处并确认原授权允许再分发。
117
+ 2. 把 `<key>.jpg` 和 `<key>.json` 放在同一个文件夹,用 `tools/pack.py` 检查并打包(有任何一条标签不合格都不会写出),再在 `sources.csv` 中登记一行:
118
+
119
+ ```bash
120
+ python tools/pack.py <文件夹> <仓库根目录> --source qdu_damo --split train
121
+ ```
122
+
123
+
124
+ | 列 | 内容 |
125
+ |---|---|
126
+ | `source` | 来源编号 |
127
+ | `team` | 队伍 |
128
+ | `year` | 采集年份 |
129
+ | `camera` | 相机、分辨率、帧率 |
130
+ | `scene` | 场地或赛事 |
131
+ | `images`、`objects` | 图像数、装甲板数 |
132
+ | `label_tool` | 标注工具 |
133
+ | `license` | 授权,如 `CC-BY-4.0` |
134
+ | `origin` | 自采,或原始链接 |
135
+
136
+ 3. 有 write 权限的维护者直接上传,其他人发 Pull Request。
137
+ 4. 每次合并新来源后打版本标签(`v1`、`v2` …),训练时固定版本:
138
+
139
+ ```python
140
+ from datasets import load_dataset
141
+ ds = load_dataset("rmcv/armor", revision="v1", split="train", streaming=True)
142
+ ```
143
+
144
+ ## 7. 授权
145
+
146
+ 数据按来源分别授权,以 `sources.csv` 为准;工具和文档采用 MIT,见 `LICENSE.md`。
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:e70083ac857c77dcc41b417836acdc34d8c45e417d8f580000fbb150891ee7bb
3
+ size 215244800
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:adeab0cf28812efd59ae9273a87570ee5651f4d48367e18b3b35cabfbdff40ba
3
+ size 144240640
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:369a20dac37bc3fcce0514a332bf77b43c5816b0daf67e46e6fc4edfc699e1cc
3
+ size 260864000
sources.csv CHANGED
@@ -1 +1,4 @@
1
  source,team,year,camera,scene,images,objects,label_tool,license,origin
 
 
 
 
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,自采
tools/export.py CHANGED
@@ -147,16 +147,16 @@ def coco_ann(ann_id, img_id, cls, obj, order, w, h, ref_ids):
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
- attrs = {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
- attrs["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": attrs,
160
  }
161
 
162
 
 
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
 
tools/pack.py ADDED
@@ -0,0 +1,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
+ ENUMS = {
23
+ "color": {"blue", "red", "gray", "purple"},
24
+ "size": {"small", "large"},
25
+ "corner_def": {"sjtu4", "unspecified"},
26
+ "label_type": {"human", "human_checked", "model"},
27
+ "role": {"positive", "ignore", "negative"},
28
+ }
29
+ FLAGS = {"truncated", "occluded", "motion_blur", "overexposed", "unlit"}
30
+ STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
31
+
32
+
33
+ def check(label, jpg, stickers):
34
+ """Return a list of problems for one image."""
35
+ errors = []
36
+ image = label.get("image", {})
37
+ try:
38
+ w, h = Image.open(io.BytesIO(jpg)).size
39
+ except Exception as e: # unreadable image
40
+ return [f"image: {e}"]
41
+ if (image.get("width"), image.get("height")) != (w, h):
42
+ errors.append(f"image size {image.get('width')}x{image.get('height')} != jpg {w}x{h}")
43
+ for i, obj in enumerate(label.get("objects", [])):
44
+ where = f"objects[{i}]"
45
+ if "corners" not in obj and "bbox" not in obj:
46
+ errors.append(f"{where}: needs corners or bbox")
47
+ if "corners" in obj:
48
+ q = obj["corners"]
49
+ if len(q) != 4 or any(len(p) != 2 for p in q):
50
+ errors.append(f"{where}: corners must be 4 [x, y] points")
51
+ else:
52
+ area = sum(q[k][0] * q[(k + 1) % 4][1] - q[k][1] * q[(k + 1) % 4][0] for k in range(4))
53
+ if area >= 0:
54
+ errors.append(f"{where}: corners not LT, LB, RB, RT counter-clockwise")
55
+ if "bbox" in obj and (len(obj["bbox"]) != 4 or obj["bbox"][2] <= 0 or obj["bbox"][3] <= 0):
56
+ errors.append(f"{where}: bbox must be [x, y, w, h] with w, h > 0")
57
+ for key, allowed in ENUMS.items():
58
+ if key in obj and obj[key] not in allowed:
59
+ errors.append(f"{where}: {key}={obj[key]!r}")
60
+ if "sticker" in obj and obj["sticker"] not in stickers:
61
+ errors.append(f"{where}: sticker={obj['sticker']!r} not in stickers.json")
62
+ if "visibility" in obj and (len(obj["visibility"]) != 4 or set(obj["visibility"]) - {0, 1, 2}):
63
+ errors.append(f"{where}: visibility must be 4 values of 0/1/2")
64
+ if set(obj.get("flags", [])) - FLAGS:
65
+ errors.append(f"{where}: unknown flags {sorted(set(obj['flags']) - FLAGS)}")
66
+ return errors
67
+
68
+
69
+ def main():
70
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
71
+ ap.add_argument("input_dir")
72
+ ap.add_argument("dataset_root")
73
+ ap.add_argument("--source", required=True)
74
+ ap.add_argument("--split", required=True, choices=["train", "test"])
75
+ ap.add_argument("--shard-mb", type=int, default=1024)
76
+ args = ap.parse_args()
77
+
78
+ if not re.fullmatch(r"[a-z0-9_]+", args.source):
79
+ sys.exit("source must use lowercase letters, digits and underscores")
80
+ stickers = {s["id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
81
+
82
+ pairs, problems = [], []
83
+ for json_path in sorted(Path(args.input_dir).rglob("*.json")):
84
+ jpg_path = json_path.with_suffix(".jpg")
85
+ if not jpg_path.exists():
86
+ continue
87
+ label = json.loads(json_path.read_text("utf-8"))
88
+ label.setdefault("image", {})["source"] = args.source
89
+ jpg = jpg_path.read_bytes()
90
+ problems += [f"{json_path.name}: {e}" for e in check(label, jpg, stickers)]
91
+ pairs.append((json_path.stem, jpg, label))
92
+ if problems:
93
+ print("\n".join(problems[:50]))
94
+ sys.exit(f"{len(problems)} problems, nothing written")
95
+ if not pairs:
96
+ sys.exit("no <key>.jpg + <key>.json pairs found")
97
+
98
+ out_dir = Path(args.dataset_root) / "data" / args.source / args.split
99
+ out_dir.mkdir(parents=True, exist_ok=True)
100
+ limit = args.shard_mb * 1024 * 1024
101
+ shard, size, tar, counts = 0, 0, None, {"images": 0, "objects": 0, "shards": 0}
102
+ for key, jpg, label in pairs:
103
+ data = json.dumps(label, ensure_ascii=False).encode("utf-8")
104
+ if tar is None or size + len(jpg) + len(data) > limit:
105
+ if tar:
106
+ tar.close()
107
+ tar = tarfile.open(out_dir / f"{args.source}-{args.split}-{shard:05d}.tar", "w")
108
+ shard, size = shard + 1, 0
109
+ counts["shards"] += 1
110
+ for ext, payload in (("jpg", jpg), ("json", data)):
111
+ info = tarfile.TarInfo(f"{key}.{ext}")
112
+ info.size = len(payload)
113
+ tar.addfile(info, io.BytesIO(payload))
114
+ size += len(jpg) + len(data) + 2048
115
+ counts["images"] += 1
116
+ counts["objects"] += len(label.get("objects", []))
117
+ tar.close()
118
+ print(json.dumps({"out": str(out_dir), **counts}))
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()