Tutorial: analyze a recording

At its core, Rerun is a database. Rerun DB Local is a local catalog that keeps catalog metadata in memory and reads data from RRDs with a footer on demand. It can therefore serve datasets larger than RAM, while Rerun DB, our commercial managed offering for production deployments, provides persistent storage.

In this guide, we explore a query workflow by implementing an "open jaw detector" on top of our face tracking example. It has three steps:

  1. Explore a recording with the dataframe view
  2. Export the dataframe
  3. Analyze the data and send back the results

If you just want to see the final result, jump to the complete script at the end.

Explore a recording with the dataframe view

Create a recording

The first step is to create a recording in the viewer using the face tracking example. Check the face tracking installation instruction for more information on how to run this example.

Here is such a recording:

A person's face is visible and being tracked. Their jaws occasionally open and close. In the middle of the recording, the face is also temporarily hidden and no longer tracked.

Explore the data

Amongst other things, the MediaPipe Face Landmark package used by the face tracking example outputs so-called blendshapes signals, which provide information on various aspects of the face expression. These signals are logged under the /blendshapes root entity by the face tracking example.

One signal, jawOpen (logged under the /blendshapes/0/jawOpen entity as a Scalar component), is of particular interest for our purpose. Let's inspect it further using a timeseries view:

Rerun Viewer with a face tracking video of a man with his mouth open, above a time series plot of the jawOpen signal with four peaks

This signal indeed seems to jump from approximately 0.0 to 0.5 whenever the jaws are open. We also notice a discontinuity in the middle of the recording. This is due to the blendshapes being Cleared when no face is detected.

Let's create a dataframe view to further inspect the data:

Rerun Viewer with the face tracking video, the jawOpen plot and a dataframe view of jawOpen Scalar values per frame_nr

Here is how this view is configured:

  • Its content is set to /blendshapes/0/jawOpen. As a result, the table only contains columns pertaining to that entity (along with any timeline(s)). For this entity, a single column exists in the table, corresponding to the entity's single component (a Scalar).
  • The frame_nr timeline is used as index for the table. This means that the table will contain one row for each distinct value of frame_nr for which data is available.
  • The rows can further be filtered by time range. In this case, we keep the default "infinite" boundaries, so no filtering is applied.
  • The dataframe view has other advanced features which we are not using here, including filtering rows based on the existence of data for a given column, or filling empty cells with latest-at data.

Now, let's look at the actual data as represented in the above screenshot. At around frame #140, the jaws are open, and, accordingly, the jawOpen signal has values around 0.55. Shortly after, they close again and the signal decreases to below 0.1. Then, the signal becomes empty. This happens in rows corresponding to the period of time when the face cannot be tracked and all the signals are cleared.

What the exploration tells us

Our exploration of the data in the viewer so far provided us with two important pieces of information useful to implement the jaw open detector.

First, we identified that the Scalar value contained in /blendshapes/0/jawOpen contains relevant data. In particular, thresholding this signal with a value of 0.15 should provide us with a closed/opened jaw state binary indicator.

Then, we explored the numerical data in a dataframe view. The way we configured this view tells us how to query the recording from code to obtain the correct output.

Next, we query the recording from code and extract the data as a Pandas dataframe.

Export the dataframe

We now use the dataframe API of the Rerun SDK to export the same data into a Pandas dataframe, to inspect and process it further.

Load the recording

The dataframe API loads data from an .RRD file. The first step is thus to save the recording as RRD, which can be done from the Rerun menu:

Rerun menu open in the Viewer with Save recording highlighted, between Open and Save current time selection

We can then load the recording in a Python script as follows:

First perform the necessary imports,

from __future__ import annotations

from pathlib import Path

import numpy as np

import rerun as rr

then launch the server to load the recording

server = rr.server.Server(temporary=True, datasets={"tutorial": [example_rrd]})

client = rr.catalog.CatalogClient(server.url())
# On Rerun DB, connect to your deployment instead:
# client = rr.catalog.CatalogClient("rerun://api.<stack>.cloud.rerun.io")

Query the data

Once we loaded a recording, we can query it to extract some data. Here is how it is done:

dataset = client.get_dataset("tutorial")
df = dataset.filter_contents("/blendshapes/0/jawOpen").reader(index="frame_nr")

A lot is happening here, let's go step by step:

  1. We first create a view into the recording. The view specifies which content we want to use (in this case the "/blendshapes/0/jawOpen" entity).
  2. In order to perform queries a view must become a dataframe. We use the reader() call to specify this transformation where we specify our index (timeline) of interest.
  3. The object returned by reader() is a datafusion.Dataframe.

DataFusion provides a pythonic dataframe interface to your data as well as SQL querying.

Create a Pandas dataframe

Before exploring the data further, let's convert the table to a Pandas dataframe:

pd_df = df.to_pandas()

Inspect the dataframe

Let's have a first look at this dataframe:

print(pd_df)

Here is the result:

     frame_nr              frame_time  log_tick                   log_time /blendshapes/0/jawOpen:Scalars:scalars
0           0 1970-01-01 00:00:00.000        34 2024-10-13 08:26:46.819571         [0.03306490555405617]
1           1 1970-01-01 00:00:00.040        92 2024-10-13 08:26:46.866358         [0.03812221810221672]
2           2 1970-01-01 00:00:00.080       150 2024-10-13 08:26:46.899699        [0.027743922546505928]
3           3 1970-01-01 00:00:00.120       208 2024-10-13 08:26:46.934704        [0.024137917906045914]
4           4 1970-01-01 00:00:00.160       266 2024-10-13 08:26:46.967762        [0.022867577150464058]
..        ...                     ...       ...                        ...                           ...
409       409 1970-01-01 00:00:16.360     21903 2024-10-13 08:27:01.619732         [0.07283800840377808]
410       410 1970-01-01 00:00:16.400     21961 2024-10-13 08:27:01.656455         [0.07037288695573807]
411       411 1970-01-01 00:00:16.440     22019 2024-10-13 08:27:01.689784         [0.07556036114692688]
412       412 1970-01-01 00:00:16.480     22077 2024-10-13 08:27:01.722971         [0.06996039301156998]
413       413 1970-01-01 00:00:16.520     22135 2024-10-13 08:27:01.757358         [0.07366073131561279]
[414 rows x 5 columns]

We can make several observations from this output:

  • The first four columns are timeline columns. These are the various timelines the data is logged to in this recording.
  • The last column is named /blendshapes/0/jawOpen:Scalars:scalars. This is what we call a component column, and it corresponds to the Scalar component logged to the /blendshapes/0/jawOpen entity.
  • Each row in the /blendshapes/0/jawOpen:Scalars:scalars column consists of a list of (typically one) scalar.

Component columns are lists because Rerun's data model always stores components as arrays. This lets you, for example, log an entire point cloud using the Points3D archetype under a single entity and at a single timestamp.

Let's explore this further, recalling that, in our recording, no face was detected at around frame #170:

print(pd_df["/blendshapes/0/jawOpen:Scalars:scalars"][160:180])

Here is the result:

160      [0.0397215373814106]
161    [0.037685077637434006]
162      [0.0402931347489357]
163     [0.04329492896795273]
164      [0.0394592322409153]
165    [0.020853394642472267]
166                        []
167                        []
168                        []
169                        []
170                        []
171                        []
172                        []
173                        []
174                        []
175                        []
176                        []
177                        []
178                        []
179                        []
Name: /blendshapes/0/jawOpen:Scalars:scalars, dtype: object

We note that the data contains empty lists when no face is detected. When the blendshapes entities are Cleared, this happens for the corresponding timestamps and all further timestamps until a new value is logged.

While this data representation is in general useful, a flat floating point representation with NaN for missing values is typically more convenient for scalar data. This is achieved using the explode() method:

pd_df["jawOpen"] = (
    pd_df["/blendshapes/0/jawOpen:Scalars:scalars"].explode().astype(float)
)
print(pd_df["jawOpen"][160:180])

Here is the result:

160    0.039722
161    0.037685
162    0.040293
163    0.043295
164    0.039459
165    0.020853
166         NaN
167         NaN
168         NaN
169         NaN
170         NaN
171         NaN
172         NaN
173         NaN
174         NaN
175         NaN
176         NaN
177         NaN
178         NaN
179         NaN
Name: jawOpen, dtype: float64

This confirms that the newly created "jawOpen" column now contains regular, 64-bit float numbers, and missing values are represented by NaNs.

Analyze the data and send back the results

Finally, we analyze the data to extract a "jaw open state" signal and send it back to the viewer.

Analyze the data

We already identified that thresholding the jawOpen signal at 0.15 is all we need to produce a binary "jaw open state" signal.

Above, we prepared a flat, floating point column with the signal of interest called "jawOpen". Let's add a boolean column to our Pandas dataframe to hold our jaw open state:


# compute the mouth state
pd_df["jawOpenState"] = pd_df["jawOpen"] > 0.15

Send the result back to the viewer

The first step is to initialize the logging SDK targeting the same recording we just analyzed. This requires using the exact same application ID and recording ID. By using the same identifiers, we're appending new data to an existing recording. If the recording is currently open in the viewer and listening for new connections, the new data will appear in the active session in real time.

rr.init(application_id, recording_id=dataset.segment_ids()[0])
rr.connect_grpc()

We will send our jaw open state data in two forms:

  1. As a standalone Scalar component, to hold the raw data.
  2. As a Text component on the existing bounding box entity, such that we obtain a textual representation of the state in the visualization.

Here is how to send the data as a scalar:

rr.send_columns(
    "/jaw_open_state",
    indexes=[rr.TimeColumn("frame_nr", sequence=pd_df["frame_nr"])],
    columns=rr.Scalars.columns(scalars=pd_df["jawOpenState"]),
)

We use the rr.send_columns() API to efficiently send the entire column of data in a single batch.

Next, let's send the same data as Text component:

target_entity = "/video/detector/faces/0/bbox"
rr.log(target_entity, rr.Boxes2D.from_fields(show_labels=True), static=True)
rr.send_columns(
    target_entity,
    indexes=[rr.TimeColumn("frame_nr", sequence=pd_df["frame_nr"])],
    columns=rr.Boxes2D.columns(
        labels=np.where(pd_df["jawOpenState"], "OPEN", "CLOSE")
    ),
)

Here we first log the ShowLabels component as static to enable the display of the label. Then, we use rr.send_columns() again to send an entire batch of text labels. We use np.where() to produce a label matching the state for each timestamp.

Final result

With some adjustments to the viewer blueprint, we obtain the following result:

The OPEN/CLOSE label is displayed along the bounding box on the 2D view, and the /jaw_open_state signal is visible in both the timeseries and dataframe views.

Complete script

Here is the complete script used by this guide to load data, analyze it, and send the result back:

# region: imports
from __future__ import annotations

from pathlib import Path

import numpy as np

import rerun as rr

# endregion: imports

# ----------------------------------------------------------------------------
# Load and prepare the data

repo_root = Path(__file__).parent.parent.parent.parent.parent
example_rrd = (
    repo_root / "tests" / "assets" / "rrd" / "examples" / "face_tracking.rrd"
)
assert example_rrd.exists(), f"Example RRD not found at {example_rrd}"
# region: launch_server
server = rr.server.Server(temporary=True, datasets={"tutorial": [example_rrd]})

client = rr.catalog.CatalogClient(server.url())
# On Rerun DB, connect to your deployment instead:
# client = rr.catalog.CatalogClient("rerun://api.<stack>.cloud.rerun.io")
# endregion: launch_server

# query the recording into a pandas dataframe
# region: query_data
dataset = client.get_dataset("tutorial")
df = dataset.filter_contents("/blendshapes/0/jawOpen").reader(index="frame_nr")
# endregion: query_data

# region: to_pandas
pd_df = df.to_pandas()
# endregion: to_pandas

# region: print_frames
print(pd_df["/blendshapes/0/jawOpen:Scalars:scalars"][160:180])
# endregion: print_frames

# convert the "jawOpen" column to a flat list of floats
print(pd_df)
# region: explode_jaw
pd_df["jawOpen"] = (
    pd_df["/blendshapes/0/jawOpen:Scalars:scalars"].explode().astype(float)
)
print(pd_df["jawOpen"][160:180])
# endregion: explode_jaw

# ----------------------------------------------------------------------------
# Analyze the data

# region: filter_jaw

# compute the mouth state
pd_df["jawOpenState"] = pd_df["jawOpen"] > 0.15

# endregion: filter_jaw

# ----------------------------------------------------------------------------
# Log the data back to the viewer

application_id = rr.chunk.RrdReader(example_rrd).recordings()[0].application_id

# Connect to the viewer
# region: connect_viewer
rr.init(application_id, recording_id=dataset.segment_ids()[0])
rr.connect_grpc()
# endregion: connect_viewer

# log the jaw open state signal as a scalar
# region: send_columns
rr.send_columns(
    "/jaw_open_state",
    indexes=[rr.TimeColumn("frame_nr", sequence=pd_df["frame_nr"])],
    columns=rr.Scalars.columns(scalars=pd_df["jawOpenState"]),
)
# endregion: send_columns

# log a `Label` component to the face bounding box entity
# region: log_labels
target_entity = "/video/detector/faces/0/bbox"
rr.log(target_entity, rr.Boxes2D.from_fields(show_labels=True), static=True)
rr.send_columns(
    target_entity,
    indexes=[rr.TimeColumn("frame_nr", sequence=pd_df["frame_nr"])],
    columns=rr.Boxes2D.columns(
        labels=np.where(pd_df["jawOpenState"], "OPEN", "CLOSE")
    ),
)
# endregion: log_labels