Scene video and scanpath mapping#

In this tutorial, we will map gaze data from an eye-tracking recording to video frames, estimate a scanpath, and overlay the gaze fixations on the video. We will use the pyneon library to work with Neon eye-tracking recordings, which contain video and event data, including gaze information.


1. Setup: Loading a Neon Recording#

First, we load the Neon recording, which contains video and gaze data. Ensure that you have installed the required libraries such as pyneon and have the recording dataset available.

[3]:
# Import necessary libraries
import sys
import numpy as np
from pyneon import get_sample_data, Dataset, Recording
import pandas as pd


# Download sample data (if not existing) and return the path
sample_dir = get_sample_data("boardView")
print(sample_dir)

dataset_dir = sample_dir / "Timeseries Data + Scene Video"
dataset = Dataset(dataset_dir)
print(dataset)

recording = dataset[0]
C:\Users\jan-gabriel.hartel\Documents\GitHub\PyNeon\data\boardView
Dataset | 2 recordings

2. Mapping Gaze Data to Video Frames#

In Neon recordings, gaze events are not naturally synchronized with the video. To map gaze data to specific video frames, we can use the map_gaze_to_video method. This method requires the pyneon.video object for determination of video timestamps, the pyneon.fixations object to make use of PupilLabs fixation detection pipeline and the pyneon.gaze object for improved time resolution of gaze estimation.

By default, Neon reports fixations with a single coordinate. This is computed as average between all gaze coordinates over the interval dennoted as a fixation. However, this clashes with the funcional definition of a fixation as tracking a fixed point in space, used by Neon.

Imagine looking at a fixed point, for example a street sign, while you are walking past it. Despite the movement of your body and the relative movement of the sign, the fixation will be stabilised. As such, taking an average gaze coordinate over the enntire duration will not correspond to the location of the sign, or the fixation, ar any given point in time. Feeding this point into an optical flow algorithm would, with high likelihood, lead to tracking anything but the sign.

Therefore, we use partial averages of gaze locations around the respective frame’s timestamp. As the video is sampled at 30Hz while the gaze output nominally reaches 200Hz, we expect to take the average over 6 subsequent gaze points. This achieves a trade-off between recency of the reported gaze position at the given frame and error minimisation, by averaging over microsaccades around the actual fixation target as well as random errors.

[4]:
# Map gaze data to the video timestamps
synced_gaze = recording.sync_gaze_to_video(overwrite=True)

# Inspect the mapped gaze data
print(synced_gaze.data.tail())
                     gaze x [px]  gaze y [px]  worn  fixation id  blink id  \
timestamp [ns]
1732621642940900000   953.513857   416.911286     1           51      <NA>
1732621642974244444   946.757667   432.689333     1           51      <NA>
1732621643007588888   947.623000   429.558571     1           51      <NA>
1732621643040933333   948.243167   426.238667     1           51      <NA>
1732621643090933333   933.202250   428.496750     1         <NA>      <NA>

                     azimuth [deg]  elevation [deg]  frame_idx
timestamp [ns]
1732621642940900000       9.166245        12.391290        476
1732621642974244444       8.702540        11.386827        477
1732621643007588888       8.762843        11.586733        478
1732621643040933333       8.807615        11.798852        479
1732621643090933333       7.822717        11.664492        480
[5]:
recording.clear_der_dir()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[5], line 1
----> 1 recording.clear_der_dir()

AttributeError: 'Recording' object has no attribute 'clear_der_dir'

Above, we can see that each frame gets a current gaze position as well as a fixation status. Currently, three types of fixation status are used:

  1. start denoting the first frame corresponding to a fixation

  2. during corresponding to intermediate frames of the same fixation

  3. end denoting the last frame of the fixation

This determination will become relevant for tracking the scanpath with optical flow. After all, while a fixation is still active, we get up-to-date gaze information. Only after its end, tracking becomes necessary.


3. Estimating the Scanpath#

Having matched every frame with a gaze coordinate, we can now get into the meat of the scanpath estimation. In dynamic scenes, the same object will not occupy the same scene-camera location over time. Therefore, we need to continuously map past fixation points as long as they are still visible in the frame.

The estimate_scanpath method achieves this by feeding fixation point denoted as end into a Lucas-Kanade sparse optical flow algorithm. This algorithm compares the video in vicinity of the point with the subsequent frame, updating the location in dependence of its movement. While a point is tracked, its status is flagged as tracked. In practice, many scene frames will have multiple simultaneously present past fixations. Our implementation carries them and repeately performs an optical flow estimation for each point. Only when they can no longer be tracked, will they be flagged as lost and subsequently dropped for the next frame.

It should be noted that this algorithm is not optimised for performance and that it will take a considerable amount of time to run on limited hardware. For our computers, the algorithm takes roughly half the time of the video, though this benchmark heavily depends on the density of past fixation points and computational ressources

[ ]:
# Estimate the scanpath based on the mapped gaze data
recording.estimate_scanpath()

# Save the estimated scanpath as a pickle and CSV
recording.estimated_scanpath.to_pickle("estimated_scanpath.pkl")
recording.estimated_scanpath.to_csv("estimated_scanpath.csv")

# Inspect the estimated scanpath
print(recording.estimated_scanpath.head())
   time                                          fixations
0  0.00    fixation id   x   y fixation status
0       ...
1  0.05    fixation id   x   y fixation status
1       ...
2  0.10    fixation id   x   y fixation status
2       ...
3  0.15    fixation id   x   y fixation status
3       ...
4  0.20    fixation id   x   y fixation status
4       ...

We should take a moment to understand the format of the estimated_scanpath property. As we care about getting a scanpath mapped on every single video-frame, we create it as a dataframe of dataframes. As such, every row carries the timestamp of the unnderlying video and saves a dataframe in the fixations cell. In this dataframe, every present fixation is provided with an id, coordinates and a fixation status, as seen below. The benefit of treating is a dataframe is the possibility to use intuitive pandas indexing, allowing us, for example, to get a list of fixations at frame 1334. This frame corresponds to a turn with a lot of lost fixations.

As a quirk of Neon taking some time to start up, the first frames will usually not yield any usable results. Still, we carry them for consistency.

[ ]:
print(recording.estimated_scanpath["fixations"][1334])
   fixation id            x           y fixation status
0        102.0  1195.487429  495.576714          during
1         98.0    28.327660  473.548737         tracked
2         97.0   621.986206  691.748291         tracked
3         96.0   154.725586  919.655640         tracked
4         93.0   258.866272  648.244324         tracked
5         91.0    24.861883  335.163666         tracked
6         88.0          NaN         NaN            lost
7         81.0    88.962830  318.220032         tracked
8         80.0    11.042568  376.608856         tracked
9         79.0          NaN         NaN            lost
10        78.0          NaN         NaN            lost
11        74.0          NaN         NaN            lost

4. Understanding Fixation Status#

Each fixation is assigned a status that indicates its lifecycle:

  • start: first frame of fixation

  • during: intermediate frames of fixation

  • end: last frame of fixation

  • tracked: Optical flow algorithm tracks fixation

  • lost: Tracking is lost, fixation is no longer tracked and gets dropped


5. Overlaying Fixations on the Video#

Now that we have the scanpath, we can overlay the gaze fixations on the video. This creates a video output with overlaid fixations, where:

  • A blue dot represents the current gaze location.

  • Green dots represent tracked fixations.

  • A red dot indicates no fixation (saccades or blinks).

Further, we draw connecting lines between past fixations to show the scanpath for the current video. The show_video option creates a live-output of the video rendering, but also increases the runtime.

[ ]:
# Overlay the scanpath on the video and show the output
recording.overlay_scanpath_on_video("../../data/OpticalFlow/test.mp4", show_video=True)

Summary#

  • Mapping Gaze to Video: We used the map_gaze_to_video method to match gaze data with video frames based on timestamps.

  • Estimating Scanpath: The scanpath was estimated using estimate_scanpath, which tracks fixations and uses optical flow to follow past fixations across scene changes.

  • Overlaying Fixations: The fixations were visualized on the video by calling overlay_fixations_on_video.

This workflow can be used to process eye-tracking data, align it with video frames, and visualize gaze movements within video recordings.