File size: 24,132 Bytes
89ae044 | 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 | #!/usr/bin/env python3
"""Build the unified cross-view dataset from two CVAT 1.1 exports.
The script is deterministic: running it twice over the same inputs produces
byte-identical annotations, manifests and checksums (image copy order is fixed).
Usage (from anywhere):
python3 scripts/build_dataset.py \
--batch1-xml ../batch1/annotations.xml \
--batch2-xml ../batch2/annotations.xml \
--batch1-images ../Dataset-20261122T211055Z-1-001/Dataset \
--batch2-images ../Images \
--out .
It never edits the source exports and never invents annotation values.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import os
import re
import shutil
import sys
import xml.etree.ElementTree as ET
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
try:
from PIL import Image, ImageOps
except ImportError: # pragma: no cover
sys.exit("Pillow is required to read image dimensions/EXIF: pip install pillow")
BATCHES = (
# key, human label, task id (expected), attribute order
("batch1", "Pilot_Batch_001", "2785034"),
("batch2", "Pilot_Batch_002", "2798655"),
)
OBJECT_ID_RE = re.compile(r"^OBJ_\d{3}$")
VIEW_ID_RE = re.compile(r"^.+_view_\d{2,}$")
FILENAME_TS_RE = re.compile(r"^(\d{8})_(\d{6})(?:\((\d+)\))?$")
EXPECTED_ATTRS = ("object_id", "viewpoint", "lighting", "background", "distance", "view_group")
VIEWPOINTS = {"front", "back", "left", "right", "top", "bottom",
"front_left", "front_right", "back_left", "back_right", "unknown"}
LIGHTING = {"natural", "artificial", "mixed", "low_light", "flash"}
BACKGROUND = {"plain_white", "plain_dark", "plain_colored", "wood", "fabric",
"indoor_cluttered", "outdoor", "other"}
DISTANCE = {"close", "medium", "far"}
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def dhash64(path: Path) -> str:
"""64-bit difference hash, computed in EXIF-oriented display space."""
with Image.open(path) as im:
im = ImageOps.exif_transpose(im).convert("L").resize((9, 8), Image.LANCZOS)
px = list(im.get_flattened_data() if hasattr(im, "get_flattened_data") else im.getdata())
bits = 0
for y in range(8):
for x in range(8):
bits = (bits << 1) | (px[y * 9 + x] < px[y * 9 + x + 1])
return f"{bits:016x}"
def hamming(a: str, b: str) -> int:
return bin(int(a, 16) ^ int(b, 16)).count("1")
def parse_export(path: Path, batch: str, expected_task: str):
root = ET.parse(path).getroot()
version = root.findtext("version")
task = root.find("meta/task")
task_id = task.findtext("id")
task_name = task.findtext("name")
if task_id != expected_task:
raise SystemExit(f"{path}: expected task id {expected_task}, found {task_id}")
label_names = [l.findtext("name") for l in task.findall("labels/label")]
if label_names != ["object"]:
raise SystemExit(f"{path}: unexpected label set {label_names}")
images = []
for im in root.findall("image"):
boxes = im.findall("box")
if not boxes:
raise SystemExit(f"{path}: image {im.get('name')} has no annotations")
records = []
for box in boxes:
attrs = {a.get("name"): (a.text if a.text is not None else "")
for a in box.findall("attribute")}
missing = [a for a in EXPECTED_ATTRS if a not in attrs]
if missing:
raise SystemExit(f"{path}: image {im.get('name')} missing attributes {missing}")
records.append({
"label": box.get("label"),
"source": box.get("source"),
"occluded": int(box.get("occluded", 0)),
"z_order": int(box.get("z_order", 0)),
"xtl": float(box.get("xtl")),
"ytl": float(box.get("ytl")),
"xbr": float(box.get("xbr")),
"ybr": float(box.get("ybr")),
"attributes": attrs,
})
images.append({
"batch": batch,
"source_image_id": int(im.get("id")),
"name": im.get("name"),
"width": int(im.get("width")),
"height": int(im.get("height")),
"boxes": records,
})
return {
"version": version,
"task_id": task_id,
"task_name": task_name,
"subset": task.findtext("subset"),
"exported": root.findtext("meta/dumped"),
"images": images,
}
def find_source(name: str, primary: Path, fallbacks: list[Path]) -> Path:
p = primary / name
if p.is_file():
return p
for d in fallbacks:
q = d / name
if q.is_file():
return q
raise SystemExit(f"image file not found: {name} (looked in {primary} and {fallbacks})")
def capture_key(name: str):
m = FILENAME_TS_RE.match(name)
if not m:
return (99999999, 999999, 99, name)
date, clock, suffix = m.group(1), m.group(2), m.group(3)
sub = int(suffix) if suffix is not None else -1
return (int(date), int(clock), sub, name)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--batch1-xml", type=Path, required=True)
ap.add_argument("--batch2-xml", type=Path, required=True)
ap.add_argument("--batch1-images", type=Path, required=True)
ap.add_argument("--batch2-images", type=Path, required=True)
ap.add_argument("--out", type=Path, required=True, help="dataset root")
args = ap.parse_args()
out = args.out.resolve()
originals = out / "data" / "originals"
annotations_dir = out / "annotations"
metadata_dir = out / "metadata"
quality_dir = out / "quality"
for d in (originals, annotations_dir, metadata_dir, quality_dir, metadata_dir / "source_exports"):
d.mkdir(parents=True, exist_ok=True)
exports = {
"batch1": parse_export(args.batch1_xml, "batch1", "2785034"),
"batch2": parse_export(args.batch2_xml, "batch2", "2798655"),
}
source_dirs = {"batch1": args.batch1_images.resolve(), "batch2": args.batch2_images.resolve()}
other_dirs = list(source_dirs.values())
# ------------------------------------------------------------------ images
images = [] # merged image records
annotations = [] # merged annotation records (source order)
name_counts = Counter(im["name"] for exp in exports.values() for im in exp["images"])
for batch, _label, _tid in BATCHES:
exp = exports[batch]
for im in exp["images"]:
name = im["name"]
src = find_source(name, source_dirs[batch], [d for d in other_dirs if d != source_dirs[batch]])
stored = f"{Path(name).stem}__{batch}{Path(name).suffix}" if name_counts[name] > 1 else name
dst = originals / stored
shutil.copy2(src, dst)
with Image.open(dst) as pil:
exif = pil.getexif()
raw_w, raw_h = pil.size
orientation = int(exif.get(274, 1))
display = ImageOps.exif_transpose(pil).size
model = exif.get(272) or ""
try:
dto = exif.get_ifd(0x8769).get(36867) or ""
except Exception:
dto = ""
if display != (im["width"], im["height"]):
raise SystemExit(
f"{name} ({batch}): XML size {im['width']}x{im['height']} != "
f"EXIF-oriented size {display[0]}x{display[1]}"
)
image_id = f"{'b1' if batch == 'batch1' else 'b2'}_{im['source_image_id']:04d}"
digest = sha256_file(dst)
images.append({
"image_id": image_id,
"stored_filename": stored,
"original_filename": name,
"image_path": f"data/originals/{stored}",
"source_batch": batch,
"source_task_id": exp["task_id"],
"source_task_name": exp["task_name"],
"source_image_id": im["source_image_id"],
"capture_timestamp": dto.replace(":", "", 2).replace(" ", "T") if dto else "",
"device_model": model,
"width": im["width"],
"height": im["height"],
"raw_width": raw_w,
"raw_height": raw_h,
"exif_orientation": orientation,
"file_size_bytes": dst.stat().st_size,
"sha256": digest,
"dhash64": dhash64(dst),
"filename_collision": name_counts[name] > 1,
})
for box_index, box in enumerate(im["boxes"]):
annotations.append({
"source_batch": batch,
"source_task_id": exp["task_id"],
"source_task_name": exp["task_name"],
"source_image_id": im["source_image_id"],
"source_box_index": box_index,
"image_id": image_id,
"image_path": f"data/originals/{stored}",
"original_filename": name,
"image_sha256": digest,
"image_width": im["width"],
"image_height": im["height"],
"label": box["label"],
"shape_type": "rectangle",
"source": box["source"],
"occluded": box["occluded"],
"z_order": box["z_order"],
"xtl": box["xtl"],
"ytl": box["ytl"],
"xbr": box["xbr"],
"ybr": box["ybr"],
"attributes": {k: box["attributes"][k] for k in EXPECTED_ATTRS if k != "object_id"},
"object_id_raw": box["attributes"]["object_id"],
})
# Stable annotation ids in source order (batch1 then batch2, CVAT image id order).
annotations.sort(key=lambda a: (a["source_batch"], a["source_image_id"]))
for i, ann in enumerate(annotations, 1):
ann["annotation_id"] = f"ann_{i:04d}"
# ------------------------------------------------------- view id generation
groups: dict[str, list[dict]] = defaultdict(list)
for ann in annotations:
oid = ann["object_id_raw"].strip()
ann["object_id"] = oid if oid else None
if oid:
groups[oid].append(ann)
for oid, anns in groups.items():
# One view per image. If an object is annotated twice in one image we
# cannot assign two identical view ids, so the extra box is flagged and
# keeps the same view index only when the image is genuinely shared.
anns.sort(key=lambda a: (capture_key(a["original_filename"]), a["source_batch"],
a["source_image_id"], a["annotation_id"]))
per_image = Counter(a["image_id"] for a in anns)
index = 0
seen_images: dict[str, int] = {}
for a in anns:
if a["image_id"] not in seen_images:
index += 1
seen_images[a["image_id"]] = index
a["view_index"] = seen_images[a["image_id"]]
a["view_id"] = f"{oid}_view_{a['view_index']:02d}"
if per_image[a["image_id"]] > 1:
a["flags"] = ["duplicate_object_in_image"]
else:
a["flags"] = []
# object_view_count is the final total for the object, not the running
# count at the time this particular annotation was assigned its index.
total_views = len(seen_images)
for a in anns:
a["object_view_count"] = total_views
# ------------------------------------------------------------- status/flags
malformed, unresolved = [], []
for a in annotations:
oid = a["object_id"]
if oid is None:
a["view_index"] = None
a["view_id"] = None
a["object_view_count"] = 0
a["status"] = "unresolved_missing_object_id"
a["flags"] = ["missing_object_id"]
unresolved.append(a)
elif not OBJECT_ID_RE.match(oid):
a["status"] = "review_malformed_object_id"
a["flags"].append("malformed_object_id")
digits = re.sub(r"\D", "", oid)
if re.fullmatch(r"OBJ_\d{3}", f"OBJ_{digits}"):
a["suspected_object_id"] = f"OBJ_{digits}"
a["flags"].append(f"possible_typo_of:{a['suspected_object_id']}")
malformed.append(a)
else:
a["status"] = "ok"
# ------------------------------------------------------------- sort records
def object_sort_key(oid: str | None):
if oid is None:
return (2, 0, "")
if OBJECT_ID_RE.match(oid):
return (0, int(oid.split("_")[1]), oid)
return (1, 0, oid)
annotations.sort(key=lambda a: (object_sort_key(a["object_id"]),
a["view_index"] if a["view_index"] is not None else 0,
a["image_id"], a["annotation_id"]))
def ann_out(a: dict) -> dict:
return {
"annotation_id": a["annotation_id"],
"image_id": a["image_id"],
"image_path": a["image_path"],
"image_sha256": a["image_sha256"],
"image_width": a["image_width"],
"image_height": a["image_height"],
"source_batch": a["source_batch"],
"source_task_id": a["source_task_id"],
"source_task_name": a["source_task_name"],
"source_image_id": a["source_image_id"],
"source_box_index": a["source_box_index"],
"label": a["label"],
"shape_type": a["shape_type"],
"object_id": a["object_id"],
"object_id_raw": a["object_id_raw"],
"view_id": a["view_id"],
"view_index": a["view_index"],
"object_view_count": a["object_view_count"],
"bbox": {
"format": "xyxy_absolute_pixels_exif_oriented",
"xtl": round(a["xtl"], 4),
"ytl": round(a["ytl"], 4),
"xbr": round(a["xbr"], 4),
"ybr": round(a["ybr"], 4),
"width": round(a["xbr"] - a["xtl"], 4),
"height": round(a["ybr"] - a["ytl"], 4),
"area": round((a["xbr"] - a["xtl"]) * (a["ybr"] - a["ytl"]), 4),
},
"attributes": a["attributes"],
"occluded": a["occluded"],
"z_order": a["z_order"],
"source": a["source"],
"status": a["status"],
"flags": a["flags"],
**({"suspected_object_id": a["suspected_object_id"]}
if "suspected_object_id" in a else {}),
}
with (annotations_dir / "labels.jsonl").open("w", encoding="utf-8") as fh:
for a in annotations:
fh.write(json.dumps(ann_out(a), ensure_ascii=False, sort_keys=False) + "\n")
# ---------------------------------------------------------------- manifest
by_image = defaultdict(list)
for a in annotations:
by_image[a["image_id"]].append(a)
images.sort(key=lambda i: (i["source_batch"], i["source_image_id"]))
manifest_fields = ["image_id", "stored_filename", "original_filename", "image_path",
"source_batch", "source_task_id", "source_task_name", "source_image_id",
"capture_timestamp", "device_model", "width", "height",
"raw_width", "raw_height", "exif_orientation", "file_size_bytes",
"sha256", "dhash64", "n_annotations", "object_ids", "view_ids",
"filename_collision"]
with (metadata_dir / "manifest.csv").open("w", newline="", encoding="utf-8") as fh:
w = csv.DictWriter(fh, fieldnames=manifest_fields)
w.writeheader()
for im in images:
anns = sorted(by_image[im["image_id"]], key=lambda a: a["annotation_id"])
row = {k: im[k] for k in manifest_fields if k in im}
row["n_annotations"] = len(anns)
row["object_ids"] = ";".join(a["object_id"] or "" for a in anns)
row["view_ids"] = ";".join(a["view_id"] or "" for a in anns)
w.writerow(row)
# --------------------------------------------------------------- checksums
with (metadata_dir / "checksums.sha256").open("w", encoding="utf-8") as fh:
for im in sorted(images, key=lambda i: i["image_path"]):
fh.write(f"{im['sha256']} {im['image_path']}\n")
# ------------------------------------------------------------ object table
obj_rows = []
for oid in sorted(groups, key=object_sort_key):
anns = sorted(groups[oid], key=lambda a: a["view_index"])
obj_rows.append({
"object_id": oid,
"n_images": len({a["image_id"] for a in anns}),
"n_annotations": len(anns),
"n_views": len({a["view_id"] for a in anns}),
"view_ids": ";".join(a["view_id"] for a in anns),
"source_batches": ";".join(sorted({a["source_batch"] for a in anns})),
"status": "review" if any(a["status"] != "ok" for a in anns) else "ok",
})
with (metadata_dir / "objects.csv").open("w", newline="", encoding="utf-8") as fh:
w = csv.DictWriter(fh, fieldnames=list(obj_rows[0].keys()))
w.writeheader()
w.writerows(obj_rows)
# ----------------------------------------------------------- identity flags
def capture_seconds(name: str) -> int:
m = FILENAME_TS_RE.match(name)
if not m:
return 10**12
clock = m.group(2)
return int(m.group(1)) * 86400 + int(clock[0:2]) * 3600 + int(clock[2:4]) * 60 + int(clock[4:6])
def neighbours(a: dict):
"""Same-batch annotations closest in capture time, for review hints only."""
target = capture_seconds(a["original_filename"])
same = sorted((x for x in annotations
if x["source_batch"] == a["source_batch"] and x is not a),
key=lambda x: abs(capture_seconds(x["original_filename"]) - target))
return same[:2]
identity_flags = {
"missing_object_id": [
{
"annotation_id": a["annotation_id"],
"image_id": a["image_id"],
"image_path": a["image_path"],
"source_batch": a["source_batch"],
"source_image_id": a["source_image_id"],
"suspected_object_id": (neighbours(a)[0]["object_id"] if neighbours(a) else None),
"basis": "nearest-in-time annotation in the same task; NOT authoritative, "
"the raw object_id is empty in the source export",
}
for a in sorted(unresolved, key=lambda a: a["annotation_id"])
],
"malformed_object_id": [
{
"annotation_id": a["annotation_id"],
"image_id": a["image_id"],
"image_path": a["image_path"],
"object_id": a["object_id"],
"suspected_object_id": a.get("suspected_object_id"),
"note": "raw identity preserved; not merged with the suspected object",
}
for a in sorted(malformed, key=lambda a: a["annotation_id"])
],
}
(metadata_dir / "identity_flags.json").write_text(
json.dumps(identity_flags, indent=2) + "\n", encoding="utf-8")
# ------------------------------------------------------- perceptual hashes
near = []
ims = images
for i in range(len(ims)):
for j in range(i + 1, len(ims)):
d = hamming(ims[i]["dhash64"], ims[j]["dhash64"])
if d <= 8:
near.append({
"image_a": ims[i]["image_id"],
"image_b": ims[j]["image_id"],
"file_a": ims[i]["stored_filename"],
"file_b": ims[j]["stored_filename"],
"dhash_distance": d,
"object_a": ";".join(sorted({a["object_id"] or "" for a in by_image[ims[i]["image_id"]]})),
"object_b": ";".join(sorted({a["object_id"] or "" for a in by_image[ims[j]["image_id"]]})),
"review": "near-duplicate candidate; retained, verify they are distinct views",
})
near.sort(key=lambda r: (r["dhash_distance"], r["image_a"], r["image_b"]))
with (metadata_dir / "near_duplicates.csv").open("w", newline="", encoding="utf-8") as fh:
w = csv.DictWriter(fh, fieldnames=list(near[0].keys()) if near else
["image_a", "image_b", "file_a", "file_b", "dhash_distance",
"object_a", "object_b", "review"])
w.writeheader()
w.writerows(near)
# ------------------------------------------------------- excluded images list
referenced_sources = {(im["source_batch"], im["original_filename"]) for im in images}
batch2_dir = source_dirs["batch2"]
batch2_used = {n for b, n in referenced_sources if b == "batch2"}
excluded = sorted(p.name for p in batch2_dir.iterdir()
if p.is_file() and p.name not in batch2_used)
(metadata_dir / "excluded_unannotated_images.txt").write_text(
"# Files present in the supplied Images/ folder that are NOT referenced by either\n"
"# CVAT export. They are outside the two tasks and are therefore not part of the\n"
"# merged dataset (they are neither copied nor deleted).\n"
+ "".join(f"{n}\n" for n in excluded), encoding="utf-8")
# ------------------------------------------------------------ source tasks
source_tasks = {
"generated_at_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"tasks": [
{
"batch": b,
"task_id": exports[b]["task_id"],
"task_name": exports[b]["task_name"],
"cvat_version": exports[b]["version"],
"subset": exports[b]["subset"],
"exported_at": exports[b]["exported"],
"n_images": len(exports[b]["images"]),
"n_annotations": sum(len(i["boxes"]) for i in exports[b]["images"]),
"image_dir": str(source_dirs[b]),
"xml_sha256": sha256_file(Path(args.batch1_xml if b == "batch1" else args.batch2_xml)),
}
for b, _l, _t in BATCHES
],
"merged": {
"n_images": len(images),
"n_annotations": len(annotations),
"n_physical_objects": len(groups),
"n_filename_collisions": sum(1 for n, c in name_counts.items() if c > 1),
},
}
(metadata_dir / "source_tasks.json").write_text(
json.dumps(source_tasks, indent=2) + "\n", encoding="utf-8")
# keep the exact exports for lossless re-validation
shutil.copy2(args.batch1_xml, metadata_dir / "source_exports" / "batch1_annotations.xml")
shutil.copy2(args.batch2_xml, metadata_dir / "source_exports" / "batch2_annotations.xml")
# ------------------------------------------------------------------- report
print(f"images : {len(images)}")
print(f"annotations : {len(annotations)}")
print(f"objects : {len(groups)} (+{len(unresolved)} unresolved)")
print(f"views/object : min={min(len({a['view_id'] for a in v}) for v in groups.values())} "
f"max={max(len({a['view_id'] for a in v}) for v in groups.values())}")
print(f"collisions : {sum(1 for c in name_counts.values() if c > 1)} filenames")
print(f"near-dupes : {len(near)} pairs (dHash <= 8)")
print(f"excluded imgs : {len(excluded)} unannotated files in {batch2_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
|