Datasets:
File size: 6,116 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 | """Check rmcv/armor labels and pack <key>.jpg + <key>.json pairs into WebDataset tar shards.
Usage:
python pack.py <input_dir> <dataset_root> --source <source> --split train|test [--shard-mb 1024]
Writes <dataset_root>/data/<source>/<split>/<source>-<split>-00000.tar ... and prints a
summary. Every label is checked first; nothing is written if any label fails.
Requires Pillow.
"""
import argparse
import io
import json
import re
import sys
import tarfile
from pathlib import Path
from PIL import Image
IMAGE_KEYS = ["width", "height", "source", "sequence", "frame", "camera"]
OBJECT_KEYS = ["corners", "bbox", "color", "size", "sticker", "visibility", "flags",
"corner_def", "label_type", "role"]
ENUMS = {
"color": {"blue", "red", "gray", "purple"},
"size": {"small", "large"},
"corner_def": {"sjtu4", "unspecified"},
"label_type": {"human", "human_checked", "model"},
"role": {"positive", "ignore", "negative"},
}
FLAGS = {"truncated", "occluded", "motion_blur", "overexposed", "unlit"}
STICKERS = Path(__file__).resolve().parent.parent / "stickers.json"
def check(label, jpg, stickers):
"""Return a list of problems for one image."""
errors = []
image = label.get("image", {})
if set(image) - set(IMAGE_KEYS):
errors.append(f"image: unknown keys {sorted(set(image) - set(IMAGE_KEYS))}")
try:
w, h = Image.open(io.BytesIO(jpg)).size
except Exception as e: # unreadable image
return [f"image: {e}"]
if (image.get("width"), image.get("height")) != (w, h):
errors.append(f"image size {image.get('width')}x{image.get('height')} != jpg {w}x{h}")
for i, obj in enumerate(label.get("objects", [])):
where = f"objects[{i}]"
if set(obj) - set(OBJECT_KEYS):
errors.append(f"{where}: unknown keys {sorted(set(obj) - set(OBJECT_KEYS))}")
obj = {k: v for k, v in obj.items() if v is not None}
if "corners" not in obj and "bbox" not in obj:
errors.append(f"{where}: needs corners or bbox")
if "corners" in obj:
q = obj["corners"]
if len(q) != 4 or any(len(p) != 2 for p in q):
errors.append(f"{where}: corners must be 4 [x, y] points")
else:
area = sum(q[k][0] * q[(k + 1) % 4][1] - q[k][1] * q[(k + 1) % 4][0] for k in range(4))
if area >= 0:
errors.append(f"{where}: corners not LT, LB, RB, RT counter-clockwise")
if "bbox" in obj and (len(obj["bbox"]) != 4 or obj["bbox"][2] <= 0 or obj["bbox"][3] <= 0):
errors.append(f"{where}: bbox must be [x, y, w, h] with w, h > 0")
for key, allowed in ENUMS.items():
if key in obj and obj[key] not in allowed:
errors.append(f"{where}: {key}={obj[key]!r}")
if "sticker" in obj and obj["sticker"] not in stickers:
errors.append(f"{where}: sticker={obj['sticker']!r} not in stickers.json")
if "visibility" in obj and (len(obj["visibility"]) != 4 or set(obj["visibility"]) - {0, 1, 2}):
errors.append(f"{where}: visibility must be 4 values of 0/1/2")
if set(obj.get("flags", [])) - FLAGS:
errors.append(f"{where}: unknown flags {sorted(set(obj['flags']) - FLAGS)}")
return errors
def normalize(label):
"""Write every image / object with the same keys (missing -> null) so readers see one schema."""
return {"image": {k: label["image"].get(k) for k in IMAGE_KEYS},
"objects": [{k: o.get(k) for k in OBJECT_KEYS} for o in label.get("objects", [])]}
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input_dir")
ap.add_argument("dataset_root")
ap.add_argument("--source", required=True)
ap.add_argument("--split", required=True, choices=["train", "test"])
ap.add_argument("--shard-mb", type=int, default=1024)
args = ap.parse_args()
if not re.fullmatch(r"[a-z0-9_]+", args.source):
sys.exit("source must use lowercase letters, digits and underscores")
stickers = {s["id"] for s in json.loads(STICKERS.read_text("utf-8"))["stickers"]}
pairs, problems = [], []
for json_path in sorted(Path(args.input_dir).rglob("*.json")):
jpg_path = json_path.with_suffix(".jpg")
if not jpg_path.exists():
continue
label = json.loads(json_path.read_text("utf-8"))
label.setdefault("image", {})["source"] = args.source
jpg = jpg_path.read_bytes()
problems += [f"{json_path.name}: {e}" for e in check(label, jpg, stickers)]
pairs.append((json_path.stem, jpg, label))
if problems:
print("\n".join(problems[:50]))
sys.exit(f"{len(problems)} problems, nothing written")
if not pairs:
sys.exit("no <key>.jpg + <key>.json pairs found")
out_dir = Path(args.dataset_root) / "data" / args.source / args.split
out_dir.mkdir(parents=True, exist_ok=True)
limit = args.shard_mb * 1024 * 1024
shard, size, tar, counts = 0, 0, None, {"images": 0, "objects": 0, "shards": 0}
for key, jpg, label in pairs:
data = json.dumps(normalize(label), ensure_ascii=False).encode("utf-8")
if tar is None or size + len(jpg) + len(data) > limit:
if tar:
tar.close()
tar = tarfile.open(out_dir / f"{args.source}-{args.split}-{shard:05d}.tar", "w")
shard, size = shard + 1, 0
counts["shards"] += 1
for ext, payload in (("jpg", jpg), ("json", data)):
info = tarfile.TarInfo(f"{key}.{ext}")
info.size = len(payload)
tar.addfile(info, io.BytesIO(payload))
size += len(jpg) + len(data) + 2048
counts["images"] += 1
counts["objects"] += len(label.get("objects", []))
tar.close()
print(json.dumps({"out": str(out_dir), **counts}))
if __name__ == "__main__":
main()
|