← Back to the animated process

turntable_dataset.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 …
125def sort_setup_tags(poses, setup_ids, camera_table):126    """Resolve unordered setup tags into base origin, base X/Y corners, and top."""127    table_camera = inverse(camera_table)128    table_centers = {129        tag_id: transform_points(table_camera, poses[tag_id][:3, 3][None, :])[0]130        for tag_id in setup_ids131    }132    top_id = max(setup_ids, key=lambda tag_id: abs(table_centers[tag_id][2]))133    floor_ids = [tag_id for tag_id in setup_ids if tag_id != top_id]134    floor_error = max(abs(table_centers[tag_id][2]) for tag_id in floor_ids)135    top_height = abs(table_centers[top_id][2])136    if floor_error > .03:137        raise ValueError("Three setup tags must lie on the turntable surface")138    if top_height - floor_error <= .01:139        raise ValueError("One setup tag must be clearly above the three surface tags")140141    centers = {tag_id: poses[tag_id][:3, 3] for tag_id in setup_ids}142    candidates = []143    for origin_id in floor_ids:144        adjacent = [tag_id for tag_id in floor_ids if tag_id != origin_id]145        first = centers[adjacent[0]] - centers[origin_id]146        second = centers[adjacent[1]] - centers[origin_id]147        lengths = np.linalg.norm(first), np.linalg.norm(second)148        if min(lengths) <= .01:149            continue150        cosine = abs(float(np.dot(first, second) / (lengths[0] * lengths[1])))151        candidates.append((cosine, origin_id, adjacent[0], adjacent[1]))152    if not candidates:153        raise ValueError("Surface setup tags are too close together")154    cosine, origin_id, x_id, y_id = min(candidates)155    if cosine > .35:156        raise ValueError("Three surface tags must mark three corners of a rectangular base")157158    p0, px, py, ptop = [centers[tag_id] for tag_id in (origin_id, x_id, y_id, top_id)]159    if np.dot(np.cross(px - p0, py - p0), ptop - p0) < 0:160        x_id, y_id = y_id, x_id161    return {"base_origin": origin_id, "base_x": x_id,162            "base_y": y_id, "top": top_id}163164165def resolve_box_geometry(poses, setup_ids, camera_table):166    roles = sort_setup_tags(poses, setup_ids, camera_table)167    p0, p1, p2, ptop = [poses[roles[role]][:3, 3]168                         for role in ("base_origin", "base_x", "base_y", "top")]169    x = p1 - p0170    width = float(np.linalg.norm(x))171    if width <= .01:172        raise ValueError("Bottom X markers are too close")173    x /= width174    y = p2 - p0175    y -= x * np.dot(y, x)176    length = float(np.linalg.norm(y))177    if length <= .01:178        raise ValueError("Bottom Y marker is too close to the X axis")179    y /= length180    z = np.cross(x, y)181    height = float(np.dot(ptop - p0, z))182    if min(width, length, height) <= .01:183        raise ValueError("Box dimensions must each exceed 1 cm; check tag placement")184    if max(width, length, height) > 2:185        raise ValueError("Box dimension exceeds 2 m; check tag size and placement")186    camera_object = np.eye(4)187    camera_object[:3, :3] = np.column_stack((x, y, z))188    camera_object[:3, 3] = p0 + x * width / 2 + y * length / 2 + z * height / 2189    return roles, [width, length, height], camera_object190191192def calibrate(detections, intrinsic, setup_ids, permanent_ids, setup_tag_size,193              permanent_tag_size=None, max_error_px=2.5, tag_family="tag36h11"):194    permanent_tag_size = (setup_tag_size if permanent_tag_size is None195                          else permanent_tag_size)196    if tag_family not in TAG_FAMILIES:197        raise ValueError(f"Unsupported AprilTag family: {tag_family}")198    if len(set(setup_ids + permanent_ids)) != len(setup_ids + permanent_ids):199        raise ValueError("Setup and permanent tag IDs must be distinct")200    setup_poses = individual_poses(detections, setup_ids, setup_tag_size,201                                   intrinsic, max_error_px)202    permanent_poses = individual_poses(detections, permanent_ids, permanent_tag_size,203                                       intrinsic, max_error_px)204    poses = {**setup_poses, **permanent_poses}205    missing = [tag_id for tag_id in setup_ids if tag_id not in poses]206    if missing:207        raise ValueError(f"Setup tags missing or inaccurate: {missing}")208    visible = [tag_id for tag_id in permanent_ids if tag_id in poses]209    if len(visible) < 2:210        raise ValueError("Need at least two visible permanent tags to set the box")211212    # Freeze visible permanent tag corners in the first visible tag's frame.213    origin_id = visible[0]214    camera_to_table = inverse(poses[origin_id])215    board = {str(tag_id): (camera_to_table @ poses[tag_id]).tolist() for tag_id in visible}216    board[str(origin_id)] = np.eye(4).tolist()217    for tag_id in visible[1:]:218        table_tag = np.asarray(board[str(tag_id)])219        if abs(table_tag[2, 3]) > .015 or table_tag[2, 2] < .94:220            raise ValueError(f"Permanent tag {tag_id} is not coplanar with tag {origin_id}")221    camera_table, board_error = board_pose(detections, intrinsic, board, permanent_tag_size,222                                           max_error_px=max_error_px)223224    roles, dimensions, camera_object = resolve_box_geometry(poses, setup_ids, camera_table)225    table_object = inverse(camera_table) @ camera_object226    return {227        "schema_version": 3,228        "tag_family": tag_family,229        "setup_tag_size_m": setup_tag_size,230        "permanent_tag_size_m": permanent_tag_size,231        "setup_ids": sorted(setup_ids),232        "resolved_setup_roles": roles,233        "permanent_ids": sorted(permanent_ids),234        "table_frame": f"permanent_tag_{origin_id}",235        "object_frame": "box_center",236        "box_dimensions_m": dimensions,237        "T_table_object": table_object.tolist(),238        "T_table_tags": board,239        "calibration_reprojection_rms_px": board_error,240        "revision": 1,… uncited lines omitted …
302def board_pose(detections, intrinsic, board, tag_size, max_error_px=3.0):303    visible = [tag_id for tag_id in board if int(tag_id) in detections]304    if len(visible) < 2:305        raise ValueError("At least two permanent tags must be visible")306    corners = tag_corners(tag_size)307    object_points = np.concatenate([308        transform_points(np.asarray(board[tag_id]), corners) for tag_id in visible])309    image_points = np.concatenate([detections[int(tag_id)] for tag_id in visible])310    transform, error = pose_from_correspondences(object_points, image_points, intrinsic)311    if error > max_error_px:312        raise ValueError(f"Permanent tag reprojection error {error:.2f} px exceeds {max_error_px:.2f} px")313    return transform, error314315316def box_corners(dimensions):317    hx, hy, hz = np.asarray(dimensions, dtype=np.float64) / 2318    return np.array([[-hx, -hy, -hz], [hx, -hy, -hz], [-hx, hy, -hz], [hx, hy, -hz],319                     [-hx, -hy, hz], [hx, -hy, hz], [-hx, hy, hz], [hx, hy, hz]])320321322def pose_label_fields(calibration, camera_object, intrinsic, image_shape):323    points_camera = transform_points(camera_object, box_corners(calibration["box_dimensions_m"]))324    uv = project(intrinsic, points_camera)325    center = project(intrinsic, camera_object[:3, 3][None, :])[0]326    height, width = image_shape[:2]327    clipped = [max(0, float(uv[:, 0].min())), max(0, float(uv[:, 1].min())),328               min(width - 1, float(uv[:, 0].max())), min(height - 1, float(uv[:, 1].max()))]329    if clipped[2] <= clipped[0] or clipped[3] <= clipped[1]:330        raise ValueError("Object box is outside the image")331    rvec = cv2.Rodrigues(camera_object[:3, :3])[0][:, 0]332    return {333        "T_camera_object": camera_object.tolist(),334        "center_xyz_m": camera_object[:3, 3].tolist(),335        "rotation_vector_rad": rvec.tolist(),336        "center_uv_px": center.tolist(),337        "box_dimensions_m": list(calibration["box_dimensions_m"]),338        "box_corners_uv_px": uv.tolist(),339        "bbox_xyxy_px_clipped": clipped,340        "bbox_partly_outside_image": bool(np.any(uv[:, 0] < 0) or np.any(uv[:, 0] >= width)341                                          or np.any(uv[:, 1] < 0) or np.any(uv[:, 1] >= height)),342        "calibration_revision": calibration.get("revision", 1),343    }344345346def make_label(calibration, detections, intrinsic, image_shape, timestamp_ns,347               max_error_px=3.0):348    tag_size = calibration.get("permanent_tag_size_m", calibration.get("tag_size_m"))349    if tag_size is None:350        raise ValueError("Calibration is missing permanent tag size")351    camera_table, error = board_pose(detections, intrinsic, calibration["T_table_tags"],352                                     tag_size, max_error_px)353    camera_object = camera_table @ np.asarray(calibration["T_table_object"])354    height, width = image_shape[:2]355    return {356        "timestamp_ns": int(timestamp_ns),357        "camera_frame": "camera_color_optical_frame",358        "object_frame": "box_center",359        "units": "m",360        "intrinsic": intrinsic.tolist(),361        "image_size": [width, height],362        **pose_label_fields(calibration, camera_object, intrinsic, image_shape),363        "permanent_tags_used": [int(key) for key in calibration["T_table_tags"]364                                if int(key) in detections],365        "tag_reprojection_rms_px": error,