Skip to main content

scale-sensor-fusion-io

Python SDK for building, reading and validating Sensor Fusion Scene (SFS) files, the .sfs format that Scale uses for lidar, radar and camera labeling tasks.

The full format specification (every sensor and annotation field, plus prelabels and task creation) is in the Sensor Fusion Reference. This page covers the SDK.

Installation

pip install scale-sensor-fusion-io

Supported Python versions: 3.10, 3.11 and 3.12.

scale-json-binary (the .sfs encoder and decoder) is installed as a dependency.

Encoding or decoding camera video (generate_video, or reading frames from a loaded video camera) also needs an ffmpeg executable with libx264 on your PATH. pip doesn't install it: the ffmpeg-python dependency is only a wrapper. Install it with your system package manager, for example brew install ffmpeg or apt-get install ffmpeg.

Concepts

An SFS scene holds every sensor and annotation for one sequence on a single timeline:

  • Timestamps are integers in microseconds, relative to the scene's time_offset. Store absolute_time_us - time_offset, not absolute times.
  • Poses are [x, y, z, qx, qy, qz, qw]. The quaternion is scalar-last. Some libraries, such as pyquaternion, are scalar-first, so reorder before passing their values in.
  • Coordinates default to "world". Lidar and radar points are in world coordinates, and each sensor's poses give the sensor's pose in the world at each timestamp.
  • Points use typed numpy arrays: float32 positions with shape (N, 3), uint8 intensities and colors, and uint32 per-point timestamps.
  • Use time_unit="microseconds" (the default). The format also defines "nanoseconds" with uint64 per-point timestamps, but this SDK's validation rejects both, so validate_scene and parse_and_validate_scene fail on such scenes.

The SDK has two representations of a scene:

Representation Module Use it to
sfio.Scene (models) scale_sensor_fusion_io.models Build and edit scenes. Paths such as PosePath and CuboidPath are pandas DataFrames indexed by timestamp, with interpolation helpers.
SFS.Scene (spec) scale_sensor_fusion_io.spec.sfs Read and write files. Mirrors the on-disk format exactly.

Convert between them with to_scene_spec_sfs and from_scene_spec_sfs from scale_sensor_fusion_io.model_converters.

Building a scene

import numpy as np
import scale_sensor_fusion_io as sfio
from scale_sensor_fusion_io.model_converters import to_scene_spec_sfs
from scale_json_binary import JSONBinaryEncoder

time_offset = 1_700_000_000_000_000        # absolute start time, in microseconds
timestamps = [0, 100_000, 200_000]         # relative to time_offset: 3 frames at 10 Hz

# Ego poses in world coordinates: one [x, y, z, qx, qy, qz, qw] row per timestamp.
ego_poses = sfio.PosePath(
    data=[
        [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
        [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
        [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
    ],
    index=timestamps,
)

def load_points(ts):  # replace with your own loader; points must be in world coordinates
    rng = np.random.default_rng(ts)
    return rng.uniform(-20, 20, (1000, 3)).astype(np.float32), rng.integers(0, 255, 1000, dtype=np.uint8)

frames = []
for ts in timestamps:
    positions, intensities = load_points(ts)
    frames.append(
        sfio.LidarSensorFrame(
            timestamp=ts,
            points=sfio.LidarSensorPoints(positions=positions, intensities=intensities),
        )
    )

lidar = sfio.LidarSensor(id="lidar", poses=ego_poses, frames=frames)
odometry = sfio.OdometrySensor(id="odometry", poses=ego_poses)

# CuboidPath columns: x, y, z, yaw, pitch, roll, dx, dy, dz
# (center position in meters, rotation in radians, full dimensions in meters)
car = sfio.CuboidAnnotation(
    id="car-1",
    label="Car",
    path=sfio.CuboidPath(
        data=[[5.0 + i, 2.0, 0.8, 0.0, 0.0, 0.0, 4.5, 1.9, 1.6] for i in range(3)],
        index=timestamps,
    ),
)

scene = sfio.Scene(
    sensors=[lidar, odometry],
    annotations=[car],
    time_offset=time_offset,
    time_unit="microseconds",
)

JSONBinaryEncoder().write_file("scene.sfs", to_scene_spec_sfs(scene))

The model CuboidPath uses the column order above. The SFS file stores cuboids as [dx, dy, dz, x, y, z, roll, pitch, yaw]. to_scene_spec_sfs reorders the columns for you, so only use the file order when you write SFS dicts by hand.

to_scene_spec_sfs copies angles unchanged, and the Scale platform reads cuboid rotations in radians. However, CuboidPath.as_matrix() and CuboidPath.from_matrix() treat yaw, pitch and roll as degrees, and so does utils.pose_helpers.transform_path when it is applied to a CuboidPath. If you use those helpers, convert with np.degrees before and np.radians after, so the path you write still holds radians.

Cameras

A camera needs a camera-to-world PosePath, intrinsics, and either JPEG images or an MP4 video. This example continues from the one above and uses two inputs you supply:

# Your inputs: one JPEG path per timestamp, and the camera's pose in the world at each timestamp.
image_files = ["frames/000.jpg", "frames/001.jpg", "frames/002.jpg"]
camera_poses = sfio.PosePath(
    data=your_camera_to_world_poses,  # shape (3, 7): one [x, y, z, qx, qy, qz, qw] row per timestamp
    index=timestamps,
)

intrinsics = sfio.CameraIntrinsics(
    fx=1000.0, fy=1000.0, cx=960.0, cy=540.0, width=1920, height=1080,
    # Values in the parameter order of the model, here k1, k2, p1, p2, k3.
    distortion=sfio.CameraDistortion.from_values("brown_conrady", [-0.1, 0.01, 0.0, 0.0, 0.0]),
)

# Option 1: one JPEG per timestamp
images = []
for ts, path in zip(timestamps, image_files):
    with open(path, "rb") as f:
        images.append(
            sfio.CameraSensorImage(timestamp=ts, content=np.frombuffer(f.read(), dtype=np.uint8))
        )
camera = sfio.CameraSensor(id="front_camera", poses=camera_poses, intrinsics=intrinsics, images=images)

# Option 2: an MP4 (usually much smaller; see "Reducing file size").
# Needs the ffmpeg executable with libx264 (see Installation).
from scale_sensor_fusion_io.utils.video_helpers import generate_video

generate_video(image_files, "front_camera.mp4", fps=10)
with open("front_camera.mp4", "rb") as f:
    video = sfio.CameraSensorVideo(
        timestamps=timestamps, content=np.frombuffer(f.read(), dtype=np.uint8), fps=10
    )
camera = sfio.CameraSensor(id="front_camera", poses=camera_poses, intrinsics=intrinsics, video=video)

Supported distortion models: brown_conrady, fisheye, mod_kannala, mod_equi_fish, cylindrical, omnidirectional, equirectangular, fisheye_rad_tan_prism, fisheye_radial_custom, ftheta. You can also build a distortion from a dict with sfio.CameraDistortion.from_dict({"model": "brown_conrady", "k1": -0.1, ...}).

Other sensors and annotations

  • Sensors: LidarSensor, RadarSensor, CameraSensor, OdometrySensor, PointsSensor (a static point cloud) and RobotSensor.
  • Annotations: cuboid, 2D box, 2D point, 2D polyline, 2D polygon, point, top-down point, points (keypoints), polygon, top-down polygon, polyline, event, text, labeled points, localization adjustment, object and link.
  • Scene-level attributes: pass sfio.AttributePath(name=..., timestamps=..., values=...) in Scene(attributes=[...]).

The Sensor Fusion Reference documents the fields of each type.

Loading a scene

SFSLoader takes a local file path. Expand ~ yourself, because the path is opened as given.

from scale_sensor_fusion_io.loaders import SFSLoader

loader = SFSLoader("scene.sfs")

scene = loader.load()            # sfio.Scene (models): the easiest to work with
sfs_scene = loader.load_as_sfs() # SFS.Scene (spec): mirrors the file
raw = loader.load_unsafe()       # plain dict with no parsing: for repairing malformed files

# Already have the bytes (for example, from S3)?
sfs_scene = SFSLoader.load_from_bytes(raw_bytes)

Validating a scene

Validate before you create a task. Validation catches structural problems such as missing fields, wrong array shapes, mismatched lengths and timestamps that don't increase. It does not catch semantic mistakes such as the wrong quaternion order, a world/ego mix-up, or cuboid rotations in a different unit from the one the platform expects (radians). Check those by loading the scene in a test task.

A scene object:

from dataclasses import asdict
import scale_sensor_fusion_io as sfio

errors = sfio.validate_scene(scene)  # returns None when the scene is valid
if errors:
    print(asdict(errors))

A .sfs file:

from dataclasses import asdict
from scale_json_binary import read_file
from scale_sensor_fusion_io.validation import parse_and_validate_scene

result = parse_and_validate_scene(read_file("scene.sfs"))
if result.success:
    print("Scene parsed and validated successfully")
else:
    print(asdict(result))
    # {'success': False,
    #  'details': [{'path': ['sensors', 0, 'poses'],
    #               'errors': ['missing value for field "poses"']}]}

Reducing file size

Scenes that cover a long time span can grow to several GB, which makes them slow to load and can time out on upload. Two ways to shrink them:

  • Encode cameras as video. Use CameraSensorVideo with generate_video instead of individual JPEGs. MP4 compresses far better, at a small cost in image quality, which is usually fine for 3D labeling.

  • Downsample point clouds. For cuboid annotation, voxel-downsample with voxels of at most 20 mm. A good rule of thumb for efficient loading and labeling is to keep a scene under 100,000 points. For example, keep one point per voxel in each lidar frame:

    def voxel_downsample(points: sfio.LidarSensorPoints, voxel_size: float) -> sfio.LidarSensorPoints:
        voxels = np.floor(points.positions / voxel_size).astype(np.int64)
        _, keep = np.unique(voxels, axis=0, return_index=True)
        keep.sort()
        pick = lambda a: None if a is None else a[keep]
        return sfio.LidarSensorPoints(
            positions=points.positions[keep],
            colors=pick(points.colors),
            intensities=pick(points.intensities),
            timestamps=pick(points.timestamps),
        )
    
    for frame in lidar.frames:
        frame.points = voxel_downsample(frame.points, voxel_size=0.02)
    

    scale_sensor_fusion_io.utils.downsample also has downsamplers, but they work on raw scene dicts and need intensities and per-point timestamps on every frame. downsample_scene also keeps only the first 200 frames of each lidar sensor, which truncates long scenes.

Changelog

0.6.1

  • Capped numpy<2.5 and scipy<1.17. numpy 2.5 (Python 3.12 only) breaks every SFSLoader load and parse_and_validate_scene call with TypeError: isinstance() arg 2 must be a type. scipy 1.17 breaks single-Pose math (Pose.as_transform, Pose @ Pose, interpolate_pose). If you're on 0.6.0 or 0.5.x, upgrade, or pin those two packages yourself.

0.6.0

  • Added the point_2d, polyline_2d, polygon, point, point_topdown, link, text and points annotation types.

License

Apache-2.0

Metadata

Release files for scale-sensor-fusion-io 0.6.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for scale-sensor-fusion-io 0.6.2
File Size Uploaded Provenance Actions
scale_sensor_fusion_io-0.6.2.tar.gz 54.9 kB Without provenance Details for scale_sensor_fusion_io-0.6.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for scale-sensor-fusion-io 0.6.2
File Interpreter ABI Platform Actions
scale_sensor_fusion_io-0.6.2-py3-none-any.whl Python 3 none any Details for scale_sensor_fusion_io-0.6.2-py3-none-any.whl

Total release size: 132.4 kB

Release files / scale_sensor_fusion_io-0.6.2.tar.gz

Download URL scale_sensor_fusion_io-0.6.2.tar.gz
Size 54.9 kB
Tags Source
SHA-256 checksum
How to use checksums
97a3921e026de00a095048e31191badb3c5af99e0a6e459e3c91ea7788128fd6
BLAKE2b-256 checksum
How to use checksums
7c5ab43a8e9a6f8e0ee2e2b7f70e38ae4a8e82a329f53066b90ca93d25581417
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Release files / scale_sensor_fusion_io-0.6.2-py3-none-any.whl

Download URL scale_sensor_fusion_io-0.6.2-py3-none-any.whl
Size 77.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d386900f6c2a421fc44a96f517ab7ac7d593e25083733e78c801e2fe010283c7
BLAKE2b-256 checksum
How to use checksums
5e2dd6c68c0adf7f43bea0d0102a601d4c4207c9879f29234d17618f3e3810b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.8.20

Security for scale-sensor-fusion-io 0.6.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page