Saving & Loading single cells and trajectory data

In this tutorial, we will walk through the process of saving and loading single cells and trajectory data using the livecellx library. By the end of this, you should be able to efficiently store and retrieve your single cells and trajectories json file.

# import some common libraries
import os
import glob
import os.path
import numpy as np
import json, random, cv2
from cellpose import models
from import imread
import matplotlib.pyplot as plt

from tqdm import tqdm
from pathlib import Path
from skimage import measure
from PIL import Image, ImageSequence

# from livecellx import segment
from livecellx import core
from livecellx.core import datasets
from livecellx.core import SingleCellTrajectory, SingleCellStatic
from livecellx.core.datasets import LiveCellImageDataset, SingleImageDataset

SingleCellStatic: saving & loading

Before we dive into data processing, let’s establish an output directory to save our results.

io_out_dir = Path("test_io_output")

Loading single cells from existing mask files

We are setting up the paths to the datasets that we will use throughout this tutorial. Ensure that the dataset paths provided below point to your actual datasets. The mask_dataset_path should contain your segmentation mask data, which will be used to derive individual cell information. In mask_dataset_path please make sure that the sorted (alphabetically) file names correspond to the order of times.

Note: The sorted mechanism provided simply sorts the url (file name) list according to string value. Please note that without proper left trailing zeroes, the order of final times may be incorrect. e.g. string T10 (10th file) is less than string T2. If you have your customized file patterns, please provide LiveCellImageDataset with a time2url dictionary to give necessary time information mapped to file locations for reading time-lapsed data.

# using the Path class from the pathlib module to work with file and directory paths
dataset_dir_path = Path(

mask_dataset_path = Path("../datasets/test_data_STAV-A549/mask_data")

Loading the mask dataset

We’ll now load the mask dataset using the LiveCellImageDataset class. This dataset helps segment the cells in our images.

mask_dataset = LiveCellImageDataset(mask_dataset_path, ext="png")
3 png img file paths loaded;
{0: '../datasets/test_data_STAV-A549/mask_data/seg_STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T252_XY01_DIC.tif.png',
 1: '../datasets/test_data_STAV-A549/mask_data/seg_STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T253_XY01_DIC.tif.png',
 2: '../datasets/test_data_STAV-A549/mask_data/seg_STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T254_XY01_DIC.tif.png'}

Organizing and loading DIC images

Next, we organize and load the DIC images which give us a detailed and contrasting view of cell boundaries.

# using the glob module to list all relevant files to load the dataset.
time2url = sorted(glob.glob(str((Path(dataset_dir_path) / Path("*_DIC.tif")))))
time2url = {i: path for i, path in enumerate(time2url)}
dic_dataset = LiveCellImageDataset(time2url=time2url, ext="tif")
# dic_dataset = LiveCellImageDataset(dataset_dir_path, ext="tif")

We check if the time2url mapping is correct

{0: '../datasets/test_data_STAV-A549/DIC_data/STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T252_XY01_DIC.tif',
 1: '../datasets/test_data_STAV-A549/DIC_data/STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T253_XY01_DIC.tif',
 2: '../datasets/test_data_STAV-A549/DIC_data/STAV-A549_VIM_24hours_NoTreat_NA_YL_Ti2e_2022-12-21_T254_XY01_DIC.tif'}

Preparing single cells from mask dataset

Using the mask dataset and DIC images, we will now prepare the single cell data.

from skimage.measure import regionprops
from livecellx.core.io_sc import prep_scs_from_mask_dataset
single_cells = prep_scs_from_mask_dataset(mask_dataset, dic_dataset)
100%|██████████| 3/3 [00:09<00:00,  3.30s/it]
{'label_in_mask': 2}

Saving single cells to JSON

Here, we save the single cell data into a JSON file for future use.

sc_json_list = SingleCellStatic.write_single_cells_json(single_cells, io_out_dir/"single_cells.json", dataset_dir=io_out_dir/"dataset", return_list=True)

Loading single cells from JSON

Once saved, you can easily load this data back into your workspace.

loaded_scs = SingleCellStatic.load_single_cells_json(io_out_dir/"single_cells.json")
SingleCellStatic(id=07c0b946-b728-4da9-bbd6-0136007364ad, timeframe=0, bbox=[ 143.  978.  207. 1044.])

We may check the first two single cells data

for sc in single_cells[:2]:

To ensure data integrity, you might want to compare the loaded data with the original

for sc in single_cells:
    for loaded_sc in loaded_scs:
        if ==
            # compare contour, contours are np.array
            assert np.allclose(sc.contour, loaded_sc.contour), f"the difference between sc.contour and loaded_sc.contour is {sc.contour - loaded_sc.contour}, ids are {} and {}"

SingleCellTrajectory: saving & loading

Tracking single cells for trajectories

To track the movement of cells across different frames, we will now generate trajectories for each cell.

from typing import List
from livecellx.track.sort_tracker_utils import (

sct_collection = track_SORT_bbox_from_scs(single_cells, dic_dataset, mask_dataset=mask_dataset, max_age=1, min_hits=1)

Saving the Trajectories

Finally, we save the generated trajectories for future reference