← Back to the animated process

scripts/build_calibrated_reference.py

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 …
30def rigid(value):31    transform = np.asarray(value, dtype=np.float64)32    if (transform.shape != (4, 4) or not np.isfinite(transform).all()33            or not np.allclose(transform[3], [0, 0, 0, 1], atol=1e-6)34            or not np.allclose(transform[:3, :3].T @ transform[:3, :3], np.eye(3), atol=1e-5)35            or not np.isclose(np.linalg.det(transform[:3, :3]), 1, atol=1e-5)):36        raise ValueError('Capture T_camera_object must be a finite rigid transform')37    return transform383940def build(dataset, masks, output, voxel_mm=2.5, truncation_mm=12.5,41          box_margin_mm=3.0, min_views=8, min_points=1000, excluded_stems=()):42    dataset, masks, manifest_path, manifest, records = resolve_augmentation(dataset, masks)43    calibration = json.loads((dataset / 'calibration.json').read_text())44    items, dimensions, readiness = preflight(dataset, masks, records)45    if not readiness['ready']:46        raise ValueError(f'Incomplete capture/mask pairs: {readiness["missing_counts"]}')47    if (calibration.get('object_frame') != 'box_center'48            or dimensions is None49            or not np.allclose(dimensions, calibration['box_dimensions_m'], atol=1e-8, rtol=0)):50        raise ValueError('Capture box differs from the current calibration')51    if not (0 < voxel_mm <= 10 and voxel_mm < truncation_mm <= 5052            and 0 <= box_margin_mm <= 20 and min_views >= 1 and min_points >= 30):53        raise ValueError('Invalid TSDF or reference quality settings')54    excluded = set(excluded_stems)55    items = [item for item in items if item[0] not in excluded]56    if len(items) < min_views:57        raise ValueError(f'Need at least {min_views} calibrated views, found {len(items)}')58    output = Path(output).resolve()59    if output.exists():60        raise FileExistsError(f'Reference already exists: {output}')6162    volume = o3d.pipelines.integration.ScalableTSDFVolume(63        voxel_length=voxel_mm / 1000, sdf_trunc=truncation_mm / 1000,64        color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8)65    rows = []66    for stem, _label_path, label, *_ in items:67        if (label.get('object_frame') != 'box_center'68                or label.get('calibration_revision') != calibration.get('revision')69                or label.get('camera_frame') not in ('color_optical_frame',70                                                     'camera_color_optical_frame')71                or label.get('depth_aligned_to') != 'rectified color image'):72            raise ValueError(f'Capture frame differs from calibration: {stem}')73        camera_object = rigid(label['T_camera_object'])74        image_bgr, depth, mask = read_inputs((stem, _label_path, label, *_))75        _foreground, ys, xs, _camera, _object, metrics = extract_masked_object_points(76            depth, mask, label, box_tolerance_ratio=0.08)77        if len(xs) < 100:78            raise ValueError(f'Too few valid masked depth pixels in {stem}: {len(xs)}')79        filtered_depth = np.zeros_like(depth)80        filtered_depth[ys, xs] = depth[ys, xs]81        intrinsic = np.asarray(label['intrinsic'], dtype=np.float64)82        height, width = depth.shape83        camera = o3d.camera.PinholeCameraIntrinsic(84            width, height, intrinsic[0, 0], intrinsic[1, 1],85            intrinsic[0, 2], intrinsic[1, 2])86        rgb = np.ascontiguousarray(cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB))87        rgbd = o3d.geometry.RGBDImage.create_from_color_and_depth(88            o3d.geometry.Image(rgb), o3d.geometry.Image(filtered_depth),89            depth_scale=1.0 / float(label['depth_unit_m']),90            depth_trunc=float(label['depth_range_m'][1]),91            convert_rgb_to_intensity=False)92        volume.integrate(rgbd, camera, camera_object)93        rows.append(dict(stem=stem, valid_depth_pixels=int(len(xs)),94                         tag_reprojection_rms_px=label.get('tag_reprojection_rms_px'),95                         box_consistency=metrics['box_consistency']))9697    cloud = volume.extract_point_cloud()98    points = np.asarray(cloud.points)99    if len(points) < min_points:100        raise ValueError(f'TSDF extracted only {len(points)} points')101    half = dimensions / 2 + box_margin_mm / 1000102    inside = np.all(np.abs(points) <= half, axis=1)103    cloud = cloud.select_by_index(np.flatnonzero(inside))104    points_after_crop = len(cloud.points)105    if points_after_crop < min_points:106        raise ValueError(f'Calibrated box contains only {points_after_crop} TSDF points')107    cloud, _ = cloud.remove_statistical_outlier(nb_neighbors=20, std_ratio=2.0)108    if len(cloud.points) < min_points:109        raise ValueError(f'Only {len(cloud.points)} points remain after outlier filtering')110    cloud.estimate_normals(o3d.geometry.KDTreeSearchParamHybrid(radius=.01, max_nn=30))111    normals = np.asarray(cloud.normals)112    points = np.asarray(cloud.points)113    normals[np.einsum('ij,ij->i', normals, points) < 0] *= -1114115    metadata = dict(116        schema_version=4, name=output.name, frame_id='box_center', object_frame='box_center',117        units='m', method='calibrated_masked_rgbd_tsdf',118        transform_convention='P_camera = T_camera_object * P_object',119        reference_already_in_object_frame=True,120        T_scan_obj=np.eye(4).tolist(), T_obj_scan=np.eye(4).tolist(),121        box_dimensions_m=dimensions.tolist(), calibration_revision=calibration['revision'],122        source=dict(dataset=str(dataset), augmentation_manifest=str(manifest_path),123                    category=manifest.get('category'), views=len(rows)),124        voxel_size_mm=voxel_mm, sdf_truncation_mm=truncation_mm,125        box_margin_mm=box_margin_mm, points_before_crop=int(len(inside)),126        points_after_crop=points_after_crop, points=len(cloud.points),127        views=rows, created_utc=datetime.now(timezone.utc).isoformat())128    output.parent.mkdir(parents=True, exist_ok=True)129    stage = Path(tempfile.mkdtemp(prefix=f'.{output.name}-building-', dir=output.parent))130    try:131        if not o3d.io.write_point_cloud(str(stage / 'reference.ply'), cloud):132            raise OSError('Could not write calibrated reference PLY')133        (stage / 'frame.json').write_text(json.dumps(metadata, indent=2) + '\n')134        (stage / 'object_keypoints.yaml').write_text(object_keypoints_yaml(dimensions))135        (stage / 'README.txt').write_text(136            'This reference was fused from masked RGB-D captures with their calibrated\n'137            'T_camera_object poses. It and the eight PnP corners use box_center.\n'138            'No moving-camera scan or manual reference-axis assignment was used.\n')139        with zipfile.ZipFile(stage / 'reference_bundle.zip', 'w', zipfile.ZIP_DEFLATED) as bundle:140            for name in ('reference.ply', 'frame.json', 'object_keypoints.yaml', 'README.txt'):141                bundle.write(stage / name, arcname=f'{output.name}/{name}')142        stage.rename(output)143    finally:144        if stage.exists():145            shutil.rmtree(stage)146    print(f'Calibrated reference: {output / "reference.ply"}\n'147          f'Views: {len(rows)}; points: {len(cloud.points)}; frame: box_center')