Implementation snapshot supporting the published lesson. Only cited line ranges are included; this is not a runnable source file. Configuration and recorded examples describe this project snapshot.
… uncited lines omitted …136def normalize_keypoints(points, width, height):137 """Return eight YOLO (x, y, visibility) keypoints.138139 Visibility 2 means that a ground-truth projection is available in the image.140 Off-image projections are encoded as (0, 0, 0), never border-clipped.141 These are virtual cuboid corners, so this flag describes annotation142 availability rather than physical surface visibility.143 """144 points = np.asarray(points, dtype=np.float64)145 if points.shape != (8, 2) or not np.all(np.isfinite(points)):146 raise ValueError("box_corners_uv_px must contain eight finite 2D points")147 result = np.zeros((8, 3), dtype=np.float64)148 valid = ((points[:, 0] >= 0) & (points[:, 0] < width)149 & (points[:, 1] >= 0) & (points[:, 1] < height))150 result[valid, :2] = points[valid] / np.asarray([width, height])151 result[valid, 2] = 2… uncited lines omitted …208def sample_plan(dataset, augmentation_root, records, pair_root, validation_stems,209 include_materialized_augmentations=False):210 plan = []211 names = set()212 dimensions = None213 source_stems = {Path(row["source_image"]).stem for row in records}214 missing_validation = validation_stems - source_stems215 if missing_validation:216 raise ValueError(217 f"Validation stems are absent from augmentation manifest: "218 f"{sorted(missing_validation)}")219 for row in records:220 source_stem = Path(row["source_image"]).stem221 label_path = dataset / "labels" / f"{source_stem}.json"222 mask_path = augmentation_root / row.get("mask", f"masks/{source_stem}.png")223 if not label_path.is_file():224 raise ValueError(f"Missing rich pose label: {label_path}")225 if not mask_path.is_file():226 raise ValueError(f"Missing reviewed mask: {mask_path}")227 label = json.loads(label_path.read_text())228 current_dimensions = np.asarray(label.get("box_dimensions_m"), dtype=np.float64)229 if current_dimensions.shape != (3,) or np.any(current_dimensions <= 0):230 raise ValueError(f"Invalid box dimensions in {label_path}")231 if dimensions is None:232 dimensions = current_dimensions233 elif not np.allclose(current_dimensions, dimensions, atol=1e-9, rtol=0):234 raise ValueError("All labels must use one canonical object box revision")235 source_image = Path(row["source_image"]).resolve()236 if not source_image.is_file():237 generated_original = (row.get("generated") or [{}])[0].get("name", "")238 fallback = pair_root / generated_original239 if (Path(generated_original).stem == source_stem and fallback.is_file()):240 source_image = fallback241 if not source_image.is_file() or source_image.suffix.lower() not in IMAGE_SUFFIXES:242 raise ValueError(f"Missing or unsupported source image: {source_image}")243 original = {"name": source_image.name, "pixel_sha256": None,244 "image_path": source_image}245 generated = row.get("generated", [])246 if include_materialized_augmentations:247 if (not generated248 or Path(generated[0].get("name", "")).stem != source_stem249 or not pair_root.is_dir()):250 raise ValueError(251 f"Materialized augmentation pairs are missing for {source_stem}")252 choices = generated253 else:254 choices = (original,)255 if source_stem in validation_stems:256 selected = (("val", original),)257 else:258 selected = (("train", item) for item in choices)259 for split, item in selected:260 name = item.get("name", "")261 image_path = Path(item.get("image_path", pair_root / name))262 if Path(name).suffix.lower() not in IMAGE_SUFFIXES or not image_path.is_file():263 raise ValueError(f"Missing or unsupported augmented image: {image_path}")264 stem = Path(name).stem265 if stem in names:266 raise ValueError(f"Duplicate generated sample stem: {stem}")267 names.add(stem)268 plan.append({269 "split": split,270 "name": name,271 "stem": stem,272 "source_stem": source_stem,273 "image_path": image_path,274 "label_path": label_path,275 "mask_path": mask_path,276 "label": label,277 "original": stem == source_stem,278 "pixel_sha256": item.get("pixel_sha256"),279 })280 if not plan or dimensions is None:281 raise ValueError("No paired samples found")282 return plan, dimensions283284285def validation_split(records, fraction=0.125, seed=317):286 """Choose held-out source views without relying on materialized augmentations."""287 if not 0 < fraction < 0.5:288 raise ValueError("Validation fraction must be greater than 0 and less than 0.5")289 if len(records) < 4:290 raise ValueError("At least four source views are required for a validation split")291 count = max(1, min(len(records) - 1, int(round(len(records) * fraction))))292 indices = list(range(len(records)))293 random.Random(seed).shuffle(indices)294 return {Path(records[index]["source_image"]).stem for index in indices[:count]}… uncited lines omitted …389 for item in plan:390 source_stem = item["source_stem"]391 if source_stem not in source_cache:392 label = item["label"]393 width, height = (int(value) for value in label.get("image_size", ()))394 mask = read_mask(item["mask_path"])395 if mask.shape != (height, width):396 raise ValueError(397 f"Mask shape {mask.shape} differs from label image size "398 f"{(height, width)} for {source_stem}")399 polygons, holes = mask_to_polygons(400 mask, min_polygon_area, epsilon_ratio)401 if len(polygons) != 1:402 raise ValueError(403 f"Expected one object polygon for {source_stem}; "404 f"found {len(polygons)} after {min_polygon_area:g} px^2 filtering")405 polygon = polygons[0]406 polygon_iou = polygon_mask_iou(mask, polygon)407 if polygon_iou < min_polygon_mask_iou:408 raise ValueError(409 f"Polygon/mask disagreement for {source_stem}: IoU "410 f"{polygon_iou:.4f} < {min_polygon_mask_iou:.4f}")411 bbox = mask_bbox(mask)412 keypoints_px = np.asarray(label.get("box_corners_uv_px"), dtype=np.float64)413 if "intrinsic" in label and "T_camera_object" in label:414 intrinsic = np.asarray(label["intrinsic"], dtype=np.float64)415 camera_object = np.asarray(label["T_camera_object"], dtype=np.float64)416 if intrinsic.shape != (3, 3) or camera_object.shape != (4, 4):417 raise ValueError(f"Invalid camera geometry in {item['label_path']}")418 expected = project(419 intrinsic,420 transform_points(camera_object, box_corners(dimensions)))421 if not np.allclose(keypoints_px, expected, atol=1e-4, rtol=0):422 raise ValueError(423 f"Stored 2D keypoints do not match canonical box projection: "424 f"{item['label_path']}")425 source_cache[source_stem] = {426 "width": width,427 "height": height,428 "mask": mask,429 "polygon_px": polygon,430 "polygon_normalized": normalize_polygon(polygon, width, height),431 "polygon_mask_iou": polygon_iou,432 "polygon_vertices": int(len(polygon)),433 "holes_omitted": holes,434 "external_components": len(polygons),435 "bbox_px": bbox,436 "bbox_normalized": normalize_bbox(bbox, width, height),437 "keypoints_px": keypoints_px,438 "keypoints_normalized": normalize_keypoints(keypoints_px, width, height),… uncited lines omitted …557 parser.add_argument("--dataset", type=Path, default=ROOT / "datasets/my_object",558 help="Turntable dataset containing labels/ (default: datasets/my_object)")559 parser.add_argument("--augmentation-root", type=Path,560 help="Reviewed mask/augmentation output (default: *_clean, then standard)")561 parser.add_argument("--split-manifest", type=Path,562 help="Optional source-grouped split.json (auto-detected in the dataset)")563 parser.add_argument("--val-fraction", type=float, default=0.125,564 help="Source-view validation fraction when no split manifest exists (default: 0.125)")565 parser.add_argument("--split-seed", type=int, default=317,566 help="Deterministic validation split seed (default: 317)")567 parser.add_argument("--output", type=Path,568 default=ROOT / "datasets/my_object/yolo_seg_pose",569 help="New output directory; must not already exist")570 parser.add_argument("--class-name", help="YOLO class name (default: augmentation category)")571 parser.add_argument("--copy-images", action="store_true",572 help="Copy images instead of creating space-saving relative symlinks")573 parser.add_argument("--include-materialized-augmentations", action="store_true",574 help="Legacy mode: export pre-generated background images from outf/")575 parser.add_argument("--polygon-epsilon", type=float, default=0.001,576 help="Contour approximation ratio (default: 0.001)")577 parser.add_argument("--min-polygon-area", type=float, default=100,578 help="Ignore external regions smaller than this pixel area (default: 100)")579 parser.add_argument("--min-polygon-mask-iou", type=float, default=0.98,580 help="Reject lossy polygon conversion below this IoU (default: 0.98)")