cellpick.app package

Contents

cellpick.app package#

This package provides the main application components for CellPick.

Core Module#

The core module contains fundamental data structures and state management.

cellpick.app.core.state#

Application state management including AppState, DataLoadMode, and AppStateManager.

Application state management for CellPick.

This module provides the AppStateManager class that manages the entire application state, including shapes, landmarks, active regions, and UI state.

class cellpick.app.core.state.AppState(*values)#

Bases: Enum

Enum representing the application state.

HOME#

Initial home state.

Type:

auto

ADV_HOME#

Advanced home state with additional options.

Type:

auto

MAIN#

Main working state.

Type:

auto

SELECTING_LND#

Selecting landmark points.

Type:

auto

DELETING_LND#

Deleting landmarks.

Type:

auto

SELECTING_AR#

Selecting active region points.

Type:

auto

DELETING_AR#

Deleting active regions.

Type:

auto

ADDING_SHP#

Adding shapes to selection.

Type:

auto

DELETING_SHP#

Deleting shapes from selection.

Type:

auto

SELECTING_CLB#

Selecting calibration points.

Type:

auto

HOME = 1#
ADV_HOME = 2#
MAIN = 3#
SELECTING_LND = 4#
DELETING_LND = 5#
SELECTING_AR = 6#
DELETING_AR = 7#
ADDING_SHP = 8#
DELETING_SHP = 9#
SELECTING_CLB = 10#
class cellpick.app.core.state.DataLoadMode(*values)#

Bases: Enum

Enum representing the data loading mode.

Once set, this determines which workflow is available.

NONE#

No data loaded yet.

Type:

auto

IMAGE#

Traditional image + XML workflow.

Type:

auto

SPATIALDATA#

SpatialData workflow.

Type:

auto

NONE = 1#
IMAGE = 2#
SPATIALDATA = 3#
class cellpick.app.core.state.AppStateManager#

Bases: object

Class to manage the application state, shapes, landmarks, and active regions.

state#

The current application state.

Type:

AppState

data_load_mode#

The current data loading mode.

Type:

DataLoadMode

image_viewer#

Reference to the image viewer.

Type:

Any

main_window#

Reference to the main window.

Type:

Any

shapes#

List of all polygons.

Type:

List[Polygon]

active_shape_ids#

Indices of active shapes.

Type:

List[int]

selected_shape_ids#

Indices of selected shapes.

Type:

List[int]

landmarks#

List of landmark point lists.

Type:

List[List[QPointF]]

current_lnd_points#

Points for the current landmark selection.

Type:

List[QPointF]

active_regions#

List of active region point lists.

Type:

List[List[QPointF]]

current_ar_points#

Points for the current active region selection.

Type:

List[QPointF]

calibration_points#

Calibration points for coordinate mapping.

Type:

List[QPointF]

cell_labels#

Dictionary mapping cell indices to their labels.

Type:

Optional[dict[int, Any]]

label_colors#

Dictionary mapping label values to RGB colors.

Type:

Optional[dict[Any, tuple[int, int, int]]]

state: AppState#
data_load_mode: DataLoadMode#
image_viewer: Any#
main_window: Any#
shapes: List[Polygon]#
active_shape_ids: List[int]#
selected_shape_ids: List[int]#
landmarks: List[List[PySide6.QtCore.QPointF]]#
current_lnd_points: List[PySide6.QtCore.QPointF]#
active_regions: List[List[PySide6.QtCore.QPointF]]#
current_ar_points: List[PySide6.QtCore.QPointF]#
calibration_points: List[PySide6.QtCore.QPointF]#
cell_labels: dict[int, Any] | None#
label_colors: dict[Any, tuple[int, int, int]] | None#
to_home()#

Set the application state to HOME and reset home buttons.

Return type:

None

enable_advanced_home()#

Set the application state to ADV_HOME and enable advanced home buttons.

Return type:

None

reset_shapes()#

Reset the shapes and related selection lists.

Return type:

None

can_add_lnd()#

Check if a new landmark can be added.

Returns:

True if less than 2 landmarks exist, False otherwise.

Return type:

bool

start_landmark_selection()#

Start the landmark selection process.

Return type:

None

add_lnd_point(point)#

Add a point to the current landmark selection.

Parameters:

point (QPointF) – The point to add.

Return type:

None

delete_last_lnd_point()#

Delete the last point from the current landmark selection.

Return type:

None

confirm_landmark()#

Confirm the current landmark selection and add it to the list.

Return type:

None

cancel_landmark()#

Cancel the current landmark selection.

Return type:

None

start_landmark_deletion()#

Start the landmark deletion process.

Return type:

None

end_landmark_deletion()#

End the landmark deletion process.

Return type:

None

try_deleting_landmark(scene_pos)#

Try to delete a landmark at the given scene position.

Parameters:

scene_pos (QPointF) – The position to check for landmark deletion.

Return type:

None

can_add_ar()#

Check if a new active region can be added.

Returns:

True if can add active regions, False otherwise.

Return type:

bool

can_load_lnd()#

Check if landmarks can be loaded from a file.

Returns:

True if can load landmarks (no existing landmarks), False otherwise.

Return type:

bool

can_load_ar()#

Check if active regions can be loaded from a file.

Returns:

True if can load active regions (no existing ARs), False otherwise.

Return type:

bool

start_ar_selection()#

Start the active region selection process.

Return type:

None

add_ar_point(point)#

Add a point to the current active region selection.

Parameters:

point (QPointF) – The point to add.

Return type:

None

delete_last_ar_point()#

Delete the last point from the current active region selection.

Return type:

None

confirm_ar()#

Confirm the current active region selection and add it to the list.

Return type:

None

cancel_ar()#

Cancel the current active region selection.

Return type:

None

start_ar_deletion()#

Start the active region deletion process.

Return type:

None

end_ar_deletion()#

End the active region deletion process.

Return type:

None

try_deleting_ar(scene_pos)#

Try to delete an active region at the given scene position.

Parameters:

scene_pos (QPointF) – The position to check for active region deletion.

Return type:

None

filter_by_ar()#

Filter shapes by active regions and update the display.

Return type:

None

update_active_shapes()#

Update active shapes based on current active regions.

Alias for filter_by_ar() for clearer semantics.

Return type:

None

select_shapes(k)#

Select k shapes from the active shapes using the configured algorithm.

Parameters:

k (int) – Number of shapes to select.

Return type:

None

try_adding_shp(scene_pos)#

Try to add a shape at the given scene position to the selection.

Parameters:

scene_pos (QPointF) – The position to check for shape addition.

Return type:

None

try_deleting_shp(scene_pos)#

Try to delete a shape at the given scene position from the selection.

Parameters:

scene_pos (QPointF) – The position to check for shape deletion.

Return type:

None

set_scores()#

Set the score for each shape based on the distance to the two landmarks.

Return type:

None

load_cell_labels(labels_dict)#

Load cell labels and generate color mapping using Tab20 or Tab10 palette.

Parameters:

labels_dict (dict[int, Any]) – Dictionary mapping cell original IDs (from segmentation mask or table instance column) to their labels.

Return type:

None

generate_label_colors()#

Generate distinct colors for each unique label.

Uses matplotlib Tab10 (≤10 labels) or Tab20 palette.

Return type:

None

clear_cell_labels()#

Clear loaded cell labels.

Return type:

None

reset_scores()#

Reset the scores for all shapes.

Return type:

None

start_calibration_selection()#

Start the calibration point selection process.

Return type:

None

end_calibration_selection()#

End the calibration point selection process.

Return type:

None

add_calibration_point(scene_pos)#

Add a calibration point at the given scene position.

Parameters:

scene_pos (QPointF) – The position of the calibration point.

Return type:

None

cellpick.app.core.polygon#

Polygon geometry utilities for shape representation.

Polygon data structures and geometry utilities.

This module provides the Polygon class for representing cell boundaries and utility functions for coordinate transformations.

cellpick.app.core.polygon.rescale_points_vectorized(points, scale_factor)#

Rescale a list of QPointF using vectorized numpy operations.

Parameters:
  • points (List[QPointF]) – The list of points to rescale.

  • scale_factor (float) – The factor to divide coordinates by.

Returns:

The rescaled points.

Return type:

List[QPointF]

class cellpick.app.core.polygon.Polygon(points, label='', original_id=None)#

Bases: object

Class representing a polygon with points, label, score, and color.

Parameters:
  • points (List[PySide6.QtCore.QPointF])

  • label (str)

  • original_id (int | None)

points#

The vertices of the polygon.

Type:

List[QPointF]

label#

The label for the polygon.

Type:

str

score#

The score associated with the polygon.

Type:

Optional[float]

color#

The color of the polygon.

Type:

QColor

original_id#

The original segmentation mask ID (if loaded from labels).

Type:

Optional[int]

points: List[PySide6.QtCore.QPointF]#
label: str#
score: float | None#
color: PySide6.QtGui.QColor#
original_id: int | None#
get_qpolygon()#

Get cached QPolygonF, creating it if necessary.

Returns:

The cached polygon for efficient rendering.

Return type:

QPolygonF

invalidate_cache()#

Invalidate the cached QPolygonF (call when points change).

Return type:

None

set_color()#

Set the color of the polygon based on its score.

If no score is set, uses magenta. Otherwise, uses a gradient from red (low score) to green (high score).

Return type:

None

centroid()#

Compute the centroid of the polygon.

Returns:

The centroid point.

Return type:

QPointF

cellpick.app.core.channel#

Image channel data structures and color mappings.

Image channel data structures for multi-channel fluorescence microscopy.

This module provides the ImageChannel dataclass for managing individual image channels with visibility, color, and saturation control.

class cellpick.app.core.channel.ImageChannel(image_data, name, visible=True, color_idx=0, custom_color=None, saturation_min=0.0, saturation_max=1.0, _raw_min=None, _raw_max=None, _processed_rgb=None, _cache_sat_min=-1.0, _cache_sat_max=-1.0)#

Bases: object

Data class representing an image channel.

Parameters:
  • image_data (numpy.ndarray)

  • name (str)

  • visible (bool)

  • color_idx (int)

  • custom_color (numpy.ndarray | None)

  • saturation_min (float)

  • saturation_max (float)

  • _raw_min (float | None)

  • _raw_max (float | None)

  • _processed_rgb (numpy.ndarray | None)

  • _cache_sat_min (float)

  • _cache_sat_max (float)

image_data#

The image data for the channel.

Type:

np.ndarray

name#

The name of the channel.

Type:

str

visible#

Whether the channel is visible.

Type:

bool

color_idx#

Index for the display color.

Type:

int

custom_color#

Custom RGB color array. If provided, overrides color_idx.

Type:

Optional[np.ndarray]

saturation_min#

Minimum saturation level (0-1 scale, maps to percentile of image).

Type:

float

saturation_max#

Maximum saturation level (0-1 scale, maps to percentile of image).

Type:

float

_raw_min#

Cached minimum value of raw image data.

Type:

Optional[float]

_raw_max#

Cached maximum value of raw image data.

Type:

Optional[float]

_processed_rgb#

Cached RGB contribution after saturation adjustment, ready to sum.

Type:

Optional[np.ndarray]

_cache_sat_min#

Saturation min value used when cache was computed.

Type:

float

_cache_sat_max#

Saturation max value used when cache was computed.

Type:

float

image_data: numpy.ndarray#
name: str#
visible: bool = True#
color_idx: int = 0#
custom_color: numpy.ndarray | None = None#
saturation_min: float = 0.0#
saturation_max: float = 1.0#
get_raw_range()#

Get the minimum and maximum values of raw image data.

Computes and caches the range on first call.

Returns:

The (min, max) values of the raw image data.

Return type:

Tuple[float, float]

compute_auto_saturation(percentile_low=1.0, percentile_high=99.0)#

Compute automatic saturation values based on percentiles.

Parameters:
  • percentile_low (float, optional) – Lower percentile for minimum saturation (default is 1.0).

  • percentile_high (float, optional) – Upper percentile for maximum saturation (default is 99.0).

Returns:

The (sat_min, sat_max) values in 0-1 scale.

Return type:

Tuple[float, float]

get_processed_rgb()#

Get the RGB contribution for this channel.

Uses cached result if saturation settings haven’t changed.

Returns:

The RGB contribution array with shape (H, W, 3).

Return type:

np.ndarray

invalidate_cache()#

Invalidate all caches.

Call this when image_data or color changes.

Return type:

None

I/O Module#

The I/O module handles file operations including XML parsing and export.

cellpick.app.io.xml_io#

XML and metadata parsing classes (DVPXML, MockDVPXML, DVPMETA, ImXML).

XML and metadata parsing for CellPick.

This module provides classes for reading DVP XML files containing shape coordinates and calibration data, as well as metadata files.

class cellpick.app.io.xml_io.DVPXML(path)#

Bases: object

Class for parsing and handling DVP XML files containing shape and calibration data.

Parameters:

path (str)

path#

Path to the XML file.

Type:

str

content#

Parsed XML content.

Type:

Any

n_shapes#

Number of shapes in the XML.

Type:

int

x_calibration#

X calibration points.

Type:

List[int]

y_calibration#

Y calibration points.

Type:

List[int]

n_shapes: int#
x_calibration: List[int]#
y_calibration: List[int]#
path: str#
content: Any#
parse_shapes()#

Parse the number of shapes from the XML content.

Return type:

None

return_shape(index)#

Return the x and y coordinates of the shape at the given index.

Parameters:

index (int) – Index of the shape to return (1-based).

Returns:

The x and y coordinates of the shape.

Return type:

Tuple[np.ndarray, np.ndarray]

read_calibration_points()#

Read calibration points from the XML content.

Return type:

None

class cellpick.app.io.xml_io.MockDVPXML(shapes)#

Bases: object

Mock DVPXML class for spatial data that doesn’t have original XML.

Provides the same interface as DVPXML for export functions.

shapes#

List of Polygon objects from the application state.

Type:

list

n_shapes#

Number of shapes.

Type:

int

x_calibration#

X calibration points (default identity mapping).

Type:

List[int]

y_calibration#

Y calibration points (default identity mapping).

Type:

List[int]

content#

Minimal XML content tree for compatibility.

Type:

etree.Element

return_shape(index)#

Return shape coordinates for the given index (1-based).

Parameters:

index (int) – Shape index (1-based).

Returns:

(x_coords, y_coords) as numpy arrays.

Return type:

Tuple[np.ndarray, np.ndarray]

class cellpick.app.io.xml_io.DVPMETA(path)#

Bases: object

Class for handling DVP metadata files.

Parameters:

path (str)

path#

Path to the metadata file.

Type:

str

metadata#

DataFrame containing the metadata.

Type:

pd.DataFrame

path: str#
metadata: pandas.DataFrame#
slice_subset(selected_slide)#

Return a subset of the metadata for the selected slide.

Parameters:

selected_slide (Any) – The slide identifier to filter by.

Returns:

Subset of the metadata for the selected slide.

Return type:

pd.DataFrame

class cellpick.app.io.xml_io.ImXML(METADATA_PATH, XML_PATH, IM_PATH)#

Bases: object

Class for handling image, XML, and metadata integration and operations.

Parameters:
  • METADATA_PATH (str)

  • XML_PATH (str)

  • IM_PATH (str)

dvpmeta#

Metadata handler.

Type:

DVPMETA

dvpxml#

XML handler.

Type:

DVPXML

im_path#

Path to the image file.

Type:

str

im#

Image data.

Type:

np.ndarray

im_shape#

Shape of the image.

Type:

Tuple[int, …]

slide#

Current slide identifier.

Type:

Any

calib_x#

X calibration values.

Type:

Any

calib_y#

Y calibration values.

Type:

Any

fxx#

Interpolator for x calibration.

Type:

Any

fyy#

Interpolator for y calibration.

Type:

Any

im: numpy.ndarray#
im_shape: Tuple[int, ...]#
slide: Any#
calib_x: Any#
calib_y: Any#
fxx: Any#
fyy: Any#
dvpmeta: DVPMETA#
dvpxml: DVPXML#
im_path: str#
load_image()#

Load the image from the file path and store its shape.

Return type:

None

bounding_rect(x, y)#

Calculate the bounding rectangle for the given x and y coordinates.

Parameters:
  • x (np.ndarray) – X-coordinates.

  • y (np.ndarray) – Y-coordinates.

Returns:

The bounding rectangle as [xmin, xmax, ymin, ymax].

Return type:

List[int]

calibration(slide)#

Calibrate the image using the selected slide’s metadata.

Parameters:

slide (Any) – The slide identifier to calibrate for.

Return type:

None

cellpick.app.io.export#

Export functions for XML, landmarks, and active regions.

Export functions for CellPick.

This module provides functions for exporting selected shapes, landmarks, and active regions to XML and CSV formats.

cellpick.app.io.export.export_xml(path, indices, dvpxml, scale=1.0)#

Select shapes with ID Shape_index in indices and export them to an XML file.

Parameters:
  • path (str) – Path to the output XML file.

  • indices (List[int]) – List of shape indices to export.

  • dvpxml (DVPXML or MockDVPXML) – The DVPXML object containing shape data.

  • scale (float, optional) – Scale factor for coordinates. Coordinates are divided by this value. Use this to rescale from display coordinates to full resolution. Default is 1.0 (no scaling).

Return type:

None

cellpick.app.io.export.export_landmarks_xml(path, landmarks, scale)#

Export landmarks (list of list of QPointF) to an XML file.

Parameters:
  • path (str) – Path to the output XML file.

  • landmarks (List[List[Any]]) – List of landmarks, where each landmark is a list of QPointF.

  • scale (float) – Scale factor for coordinates. Coordinates are divided by this value.

Return type:

None

cellpick.app.io.export.export_ar_xml(path, ars, scale)#

Export active regions (ARs) (list of list of QPointF) to an XML file.

Parameters:
  • path (str) – Path to the output XML file.

  • ars (List[List[Any]]) – List of active regions, where each AR is a list of QPointF.

  • scale (float) – Scale factor for coordinates. Coordinates are divided by this value.

Return type:

None

SpatialData Integration#

SpatialData integration module for CellPick.

This module provides functionality to load and export spatial omics data in SpatialData format (.zarr stores).

cellpick.app.spatialdata_io.extract_polygons_from_label_image(label_array, min_area=10, max_cells=100000, progress_callback=None)#

Extract polygons from a segmentation label image.

This is a standalone function that works with any numpy label array where pixel values represent cell/shape IDs (0 = background).

Parameters:
  • label_array (np.ndarray) – 2D array where each unique non-zero value represents a cell ID.

  • min_area (int) – Minimum area (in pixels) for a polygon to be included.

  • max_cells (int) – Maximum number of cells to extract (to prevent hanging on huge datasets).

  • progress_callback (Optional[callable]) – Callback function(current, total) to report progress.

Returns:

List of (polygon_points, label, original_mask_id) tuples.

Return type:

List[Tuple[List[QPointF], str, int]]

Raises:

ImportError – If scikit-image is not installed.

class cellpick.app.spatialdata_io.SpatialDataLoader(path)#

Bases: object

Loader for SpatialData .zarr stores.

Parameters:

path (str)

sdata#

The loaded SpatialData object.

Type:

SpatialData

path#

Path to the .zarr store.

Type:

Path

get_available_images()#

Get list of available image elements.

Returns:

Names of available images.

Return type:

List[str]

get_available_labels()#

Get list of available label (segmentation) elements.

Returns:

Names of available labels.

Return type:

List[str]

get_available_shapes()#

Get list of available shape elements.

Returns:

Names of available shapes.

Return type:

List[str]

get_available_tables()#

Get list of available table elements.

Returns:

Names of available tables.

Return type:

List[str]

get_available_scale_levels(image_name=None)#

Get list of available scale levels for a multiscale image.

Parameters:

image_name (Optional[str]) – Name of the image element. If None, uses the first available.

Returns:

Names of available scale levels (e.g., [‘scale0’, ‘scale1’, ‘scale2’]). Returns [‘scale0’] for single-scale images.

Return type:

List[str]

get_scale_level_info(image_name=None)#

Get information about each scale level including dimensions.

Parameters:

image_name (Optional[str]) – Name of the image element. If None, uses the first available.

Returns:

List of dicts with keys: ‘level’ (int), ‘name’ (str), ‘height’ (int), ‘width’ (int), ‘channels’ (int), ‘scale_factor’ (str).

Return type:

List[Dict[str, Any]]

get_categorical_columns(table_name=None)#

Get categorical columns from a table in the SpatialData object.

Parameters:

table_name (Optional[str]) – Name of the table to get columns from. If None, uses the first available table.

Returns:

List of categorical column names from the table.

Return type:

List[str]

get_cell_labels(label_column, table_name=None, instance_column=None)#

Get labels for each cell from a table column.

Parameters:
  • label_column (str) – Name of the column containing labels.

  • table_name (Optional[str]) – Name of the table to get labels from. If None, uses the first available table.

  • instance_column (str | None)

Returns:

Dictionary mapping cell indices (0-based) to their labels, or None if not found. The indices correspond to the order of cells as loaded into CellPick.

Return type:

Optional[Dict[int, Any]]

extract_image_channels(image_name=None, scale_level=0)#

Extract image channels from a SpatialData image element.

Parameters:
  • image_name (Optional[str]) – Name of the image element. If None, uses the first available.

  • scale_level (int) – Which scale level to extract (0 = highest resolution).

Returns:

List of channel arrays and their names.

Return type:

Tuple[List[np.ndarray], List[str]]

extract_polygons_from_labels(label_name=None, min_area=10, max_cells=10000, progress_callback=None)#

Extract polygons from segmentation labels.

Parameters:
  • label_name (Optional[str]) – Name of the label element. If None, uses the first available.

  • min_area (int) – Minimum area (in pixels) for a polygon to be included.

  • max_cells (int) – Maximum number of cells to extract (to prevent hanging on huge datasets).

  • progress_callback (Optional[callable]) – Callback function(current, total) to report progress.

Returns:

List of (polygon_points, label, original_mask_id) tuples.

Return type:

List[Tuple[List[QPointF], str, int]]

extract_polygons_from_shapes(shape_name=None)#

Extract polygons from shape elements.

Parameters:

shape_name (Optional[str]) – Name of the shape element. If None, uses the first available.

Returns:

List of (polygon_points, label) tuples.

Return type:

List[Tuple[List[QPointF], str]]

has_cellpick_annotations()#

Check if the SpatialData store contains CellPick annotations.

Returns:

True if CellPick annotations are present.

Return type:

bool

load_cellpick_selected_cells(all_cell_polygons)#

Load selected cell indices from CellPick annotations.

Matches the selected cell masks to the loaded cell polygons to find their indices.

Parameters:

all_cell_polygons (List[Tuple[List[QPointF], str]]) – All loaded cell polygons with their labels.

Returns:

List of selected cell indices (indices into all_cell_polygons).

Return type:

List[int]

load_cellpick_landmarks()#

Load landmarks from CellPick annotations.

Returns:

List of landmark point lists.

Return type:

List[List[QPointF]]

load_cellpick_active_regions()#

Load active regions from CellPick annotations.

Returns:

List of active region point lists.

Return type:

List[List[QPointF]]

static load_labels_from_csv(csv_path)#

Load labels from a CSV file.

The CSV should contain a cell ID column and at least one label column. Cell IDs can be 0-based or 1-based; the method will auto-detect and convert.

Parameters:

csv_path (str) – Path to the CSV file.

Returns:

Dictionary mapping 0-based cell indices to their labels.

Return type:

Dict[int, Any]

Raises:
  • FileNotFoundError – If the CSV file does not exist.

  • ValueError – If no suitable cell ID column is found.

class cellpick.app.spatialdata_io.SpatialDataExporter#

Bases: object

Exporter for saving CellPick data to SpatialData format.

static export_to_spatialdata(input_path, output_path, selected_polygons, landmarks=None, active_regions=None, image_shape=None, coordinate_system='global', progress_callback=None, image_channels=None, all_polygons=None)#

Export CellPick annotations to SpatialData format.

Updates an existing SpatialData store with CellPick annotations, or creates a new one from scratch if loading from image files.

Parameters:
  • input_path (Optional[str]) – Path to input .zarr store to update. If None, creates new store.

  • output_path (str) – Path where to save the .zarr store.

  • selected_polygons (List[Polygon]) – List of selected cell polygons.

  • landmarks (Optional[List[List[QPointF]]]) – List of landmark point lists.

  • active_regions (Optional[List[List[QPointF]]]) – List of active region point lists.

  • image_shape (Optional[Tuple[int, int]]) – Image dimensions (height, width) for creating label masks.

  • coordinate_system (str) – Name of the coordinate system.

  • image_channels (Optional[List[Tuple[np.ndarray, str]]]) – List of (image_data, channel_name) tuples for creating images from scratch.

  • all_polygons (Optional[List[Polygon]]) – All cell polygons (not just selected) for creating segmentation labels.

  • progress_callback (callable | None)

Raises:

ImportError – If spatialdata is not installed.

Return type:

None

static export_table_to_spatialdata(sdata_path, table_data, table_name='cell_data')#

Add a table to an existing SpatialData object.

Parameters:
  • sdata_path (str) – Path to the .zarr store.

  • table_data (pd.DataFrame) – DataFrame to add as a table.

  • table_name (str) – Name for the table element.

Return type:

None

Algorithms#

cellpick.app.algorithms.gonzalez_k_center(points, k)#

Select k centers from a set of points using the Gonzalez k-center algorithm.

Parameters:
  • points (np.ndarray) – Array of points with shape (n_points, n_features).

  • k (int) – Number of centers to select.

Returns:

Indices of the selected centers.

Return type:

List[int]

cellpick.app.algorithms.round_robin_gonzalez(points, k)#

Select k centers from a set of points using a heuristic for the fair k-center problem based on the Gonzalez k-center algorithm.

Parameters:
  • points (List[np.ndarray]) – A list of arrays of points with shape (n_points, n_features), one per class.

  • k (int) – Number of centers to select per class.

Returns:

A list of lists of indices of the selected centers.

Return type:

List[List[int]]

cellpick.app.algorithms.polygon_mindist(polys)#

FInd the minimum pairwise distance in a list of polygons.

Parameters:
  • points (np.ndarray) – Array of points with shape (n_points, n_features).

  • polys (List[List[Tuple[float, float]]])

Return type:

float

cellpick.app.algorithms.polygon_gonzalez(polys, k)#

Select k centers from a set of polygons using the Gonzalez k-center algorithm.

Parameters:
  • points (np.ndarray) – Array of points with shape (n_points, n_features).

  • k (int) – Number of centers to select.

  • polys (List[List[Tuple[float, float]]])

Returns:

Indices of the selected centers.

Return type:

List[int]

cellpick.app.algorithms.polygon_round_robin_gonzalez(polys, k)#

Select k centers from a set of polygons using a heuristic for the fair k-center problem based on the Gonzalez k-center algorithm.

Parameters:
  • points (List[List[List[Tuple[float, float]]]]) – A list of lists of polygons

  • k (int) – Number of centers to select per class.

  • polys (List[List[List[Tuple[float, float]]]])

Returns:

A list of lists of indices of the selected centers.

Return type:

List[List[int]]

cellpick.app.algorithms.dist_to_polygon(point, polygon)#

Compute the minimum distance from a point to a polygon.

Parameters:
  • point (Tuple[float, float]) – The (x, y) coordinates of the point.

  • polygon (List[Tuple[float, float]]) – List of (x, y) coordinates representing the polygon vertices.

Returns:

The minimum distance from the point to the polygon.

Return type:

float

cellpick.app.algorithms.approx_shape_distance(polygon1, polygon2)#

Compute the distance between two polygons.

Parameters:
  • polygon1 (List[Tuple[float, float]]) – List of (x, y) coordinates representing the polygon vertices.

  • polygon2 (List[Tuple[float, float]]) – List of (x, y) coordinates representing the polygon vertices.

Returns:

The approximate distance between the polygons.

Return type:

float

UI Components#

cellpick.app.ui_main#

class cellpick.app.ui_main.ScrollableContainer(*args, **kwargs)#

Bases: QWidget

A scrollable container widget with vertical layout.

Items are added from the top with a stretch at the bottom to keep content aligned to the top of the container.

Parameters:
  • height (int)

  • parent (PySide6.QtWidgets.QWidget | None)

inner_layout#

The layout where widgets are added.

Type:

QVBoxLayout

inner_layout: PySide6.QtWidgets.QVBoxLayout#
addWidget(widget)#

Add a widget to the container.

Parameters:

widget (QWidget) – The widget to add. Inserted before the stretch to keep items at top.

Return type:

None

class cellpick.app.ui_main.ResolutionSelectionDialog(*args, **kwargs)#

Bases: QDialog

Dialog for selecting image resolution level from a multiscale SpatialData image.

Displays available resolution levels with their dimensions and allows user to select which one to load.

Parameters:
  • level_info (List[dict])

  • parent (PySide6.QtWidgets.QWidget | None)

selected_level#

The selected resolution level index.

Type:

int

list_widget#

The list widget showing resolution options.

Type:

QListWidget

get_selected_level()#

Return the selected resolution level.

Returns:

The selected level index (0-based).

Return type:

int

class cellpick.app.ui_main.SelectionPage(*args, **kwargs)#

Bases: QWidget

First page of the main window for data loading and image adjustment.

Provides controls for loading channels, SpatialData, shapes, and adjusting image display settings like saturation.

channel_control_panel#

Panel for channel visibility controls.

Type:

ScrollableContainer

saturation_panel#

Panel for per-channel saturation sliders.

Type:

ScrollableContainer

add_channel_btn#

Button to add image channels.

Type:

AnimatedButton

add_spatialdata_btn#

Button to load SpatialData files.

Type:

AnimatedButton

load_shapes_btn#

Button to load shape files.

Type:

AnimatedButton

auto_saturation_checkbox#

Checkbox for auto-adjusting saturation.

Type:

QCheckBox

next_btn#

Button to proceed to the next page.

Type:

AnimatedButton

channel_control_panel: ScrollableContainer#
add_spatialdata_btn: AnimatedButton#
add_channel_btn: AnimatedButton#
load_shapes_btn: AnimatedButton#
auto_saturation_checkbox: PySide6.QtWidgets.QCheckBox#
saturation_panel: ScrollableContainer#
refresh_btn: AnimatedButton#
reset_btn: AnimatedButton#
next_btn: AnimatedButton#
buttons: List[Any]#
pick_shape_color()#

Open a color dialog to select the shape outline color.

Return type:

None

class cellpick.app.ui_main.ActionPage(*args, **kwargs)#

Bases: QWidget

Second page of the main window for shape selection and export.

Provides controls for landmarks, active regions, shape selection algorithms, and exporting results.

back_btn#

Button to return to the first page.

Type:

AnimatedButton

add_lnd_btn#

Button to add landmarks.

Type:

AnimatedButton

add_ar_btn#

Button to add active regions.

Type:

AnimatedButton

select_shapes_btn#

Button to run shape selection algorithm.

Type:

AnimatedButton

k_box#

Spinner for number of shapes to select.

Type:

QSpinBox

clustering_type#

Dropdown for selection algorithm type.

Type:

QComboBox

export_btn#

Button to export selected shapes.

Type:

AnimatedButton

export_spatialdata_btn#

Button to export to SpatialData format.

Type:

AnimatedButton

back_btn: AnimatedButton#
add_lnd_btn: AnimatedButton#
delete_last_point_lnd_btn: AnimatedButton#
confirm_lnd_btn: AnimatedButton#
cancel_lnd_btn: AnimatedButton#
delete_lnd_btn: AnimatedButton#
add_ar_btn: AnimatedButton#
delete_last_point_ar_btn: AnimatedButton#
confirm_ar_btn: AnimatedButton#
delete_ar_btn: AnimatedButton#
select_shapes_btn: AnimatedButton#
k_box: PySide6.QtWidgets.QSpinBox#
clustering_type: PySide6.QtWidgets.QComboBox#
label_checkboxes: dict#
add_shapes_btn: AnimatedButton#
rem_shapes_btn: AnimatedButton#
export_btn: AnimatedButton#
export_spatialdata_btn: AnimatedButton#
load_lnd_btn: AnimatedButton#
load_ar_btn: AnimatedButton#
buttons: List[Any]#
update_label_checkboxes(labels)#

Update the label checkboxes based on loaded labels.

Parameters:

labels (dict) – Dictionary mapping label values to RGB colors (RGB 0-255 tuples)

Return type:

None

get_selected_labels()#

Get list of selected labels from checkboxes.

Returns:

List of selected label values, or None if no labels are loaded

Return type:

Optional[List[Any]]

show_label_checkboxes(show)#

Show or hide the label checkboxes container.

Parameters:

show (bool) – Whether to show the checkboxes

Return type:

None

class cellpick.app.ui_main.MainWindow(*args, **kwargs)#

Bases: QMainWindow

Main application window for CellPick.

Manages the overall application layout, state, and coordinates between the selection page, action page, and image viewer.

state#

The application state manager.

Type:

AppStateManager

image_viewer#

The main image display widget.

Type:

ImageViewer

page1#

The data loading and image adjustment page.

Type:

SelectionPage

page2#

The shape selection and export page.

Type:

ActionPage

stack#

Widget stack for switching between pages.

Type:

QStackedWidget

scale#

Current image scale factor.

Type:

float

shape_outline_color#

Color used for shape outlines.

Type:

QColor

xml_path = None#
meta_path = None#
channels: List[str]#
state: AppStateManager#
stack: PySide6.QtWidgets.QStackedWidget#
page1: SelectionPage#
page2: ActionPage#
img_stack: PySide6.QtWidgets.QStackedWidget#
image_viewer: ImageViewer#
scale: float#
channel_control: PySide6.QtWidgets.QVBoxLayout#
shape_outline_color: PySide6.QtGui.QColor#
save_screenshot()#

Save a full-resolution screenshot of the visualization to a PNG file.

Return type:

None

toggle_shapes_visibility()#

Toggle visibility of shape overlays.

Return type:

None

toggle_color_mode()#

Toggle between showing labels and gradient colors for shapes.

Return type:

None

goto_first_page()#
Return type:

None

goto_second_page()#
Return type:

None

toggle_auto_saturation(state)#

Toggle auto-adjust saturation for all channels.

Parameters:

state (int)

Return type:

None

apply_auto_saturation()#

Apply automatic saturation to all channels based on percentiles.

Return type:

None

update_channel_saturation(channel_idx, sat_min, sat_max)#

Update saturation for a specific channel (does not update display - user must click Refresh).

Parameters:
  • channel_idx (int)

  • sat_min (float)

  • sat_max (float)

Return type:

None

reset_view()#
Return type:

None

set_image_workflow_mode()#

Set the app to IMAGE workflow mode and disable SpatialData buttons. This is irreversible without restarting the app.

Return type:

None

set_spatialdata_workflow_mode()#

Set the app to SPATIALDATA workflow mode and disable IMAGE workflow buttons. This is irreversible without restarting the app.

Return type:

None

add_channel()#
Return type:

None

add_spatialdata()#

Load data from a SpatialData .zarr store.

Return type:

None

add_channel_control(name, channel_idx)#
Parameters:
  • name (str)

  • channel_idx (int)

Return type:

None

rename_channel(channel_idx)#

Rename a channel by showing a text input dialog.

Parameters:

channel_idx (int)

Return type:

None

change_channel_color(channel_idx)#

Change a channel’s color by showing a color picker dialog.

Parameters:

channel_idx (int)

Return type:

None

remove_channel(channel_idx)#
Parameters:

channel_idx (int)

Return type:

None

rebuild_channel_controls()#
Return type:

None

toggle_channel(channel_idx, visible)#
Parameters:
  • channel_idx (int)

  • visible (bool)

Return type:

None

load_shapes()#
Return type:

None

load_calibration()#
Return type:

None

manual_calibration()#
Return type:

None

confirm_calibration()#
load_shapes_and_manual_calibrate()#
Return type:

None

load_shapes_and_load_calibrate()#
Return type:

None

load_labels()#

Load cell labels from CSV or SpatialData table.

Return type:

None

reset_home_buttons()#
Return type:

None

enable_adv_home_buttons()#
Return type:

None

reset_main_buttons()#
Return type:

None

toggle_landmark_selection()#
Return type:

None

enable_confirm_landmark()#
Return type:

None

disable_confirm_landmark()#
Return type:

None

confirm_landmark()#
Return type:

None

delete_last_lnd_point()#
Return type:

None

toggle_landmark_deletion()#
Return type:

None

toggle_ar_selection()#
Return type:

None

enable_confirm_ar(enable=True)#
Parameters:

enable (bool)

Return type:

None

enable_filter_ar(enable=True)#
Parameters:

enable (bool)

Return type:

None

confirm_ar()#
Return type:

None

delete_last_ar_point()#
Return type:

None

toggle_ar_deletion()#
Return type:

None

update_clustering_dropdown_with_labels(categorical_columns)#

Update the clustering type dropdown to include label-based grouping options.

Parameters:

categorical_columns (List[str]) – List of categorical column names from the spatial data table.

Return type:

None

select_shapes()#
Return type:

None

on_clustering_type_changed(index)#

Handle clustering type selection changes. Show label checkboxes when ‘Select k per label’ is selected.

Parameters:

index (int) – Index of the selected clustering type

Return type:

None

toggle_shape_add()#
Return type:

None

toggle_shape_rem()#
Return type:

None

export_to_spatialdata()#

Export CellPick annotations to SpatialData format.

Return type:

None

export_selected_shapes()#

Export selected shapes to XML and CSV after prompting for a base file name.

Return type:

None

load_landmarks_from_file()#
load_ar_from_file()#

cellpick.app.ui_components#

class cellpick.app.ui_components.RangeSlider(*args, **kwargs)#

Bases: QWidget

A dual-handle range slider for min/max value selection.

Mimics the Cellpose saturation slider style with draggable handles for setting minimum and maximum values in a 0-1 range.

Parameters:
  • color (Tuple[int, int, int])

  • parent (PySide6.QtWidgets.QWidget | None)

rangeChanged#

Emitted when either handle is moved. Carries (min_val, max_val) as floats.

Type:

Signal

color#

RGB color for the active range display.

Type:

Tuple[int, int, int]

rangeChanged#

alias of float

property min_val: float#

The current minimum value (0-1 scale).

Type:

float

property max_val: float#

The current maximum value (0-1 scale).

Type:

float

set_range(min_val, max_val)#

Set the range values.

Parameters:
  • min_val (float) – Minimum value (clamped to 0-1).

  • max_val (float) – Maximum value (clamped to 0-1).

Return type:

None

set_color(color)#

Update the slider color.

Parameters:

color (Tuple[int, int, int]) – RGB color for the active range.

Return type:

None

paintEvent(event)#

Paint the slider track, active range, and handles.

Return type:

None

mousePressEvent(event)#

Handle mouse press to start dragging a handle.

Parameters:

event (PySide6.QtGui.QMouseEvent)

Return type:

None

mouseMoveEvent(event)#

Handle mouse move to update handle position.

Parameters:

event (PySide6.QtGui.QMouseEvent)

Return type:

None

mouseReleaseEvent(event)#

Handle mouse release to stop dragging.

Parameters:

event (PySide6.QtGui.QMouseEvent)

Return type:

None

class cellpick.app.ui_components.AnimatedButton(*args, **kwargs)#

Bases: QPushButton

A styled QPushButton with rounded corners and press animation.

Provides a modern dark theme button with customizable colors and smooth pressed/unpressed state styling.

Parameters:
  • text (str)

  • size (Tuple[int, int])

  • color1 (str)

  • color2 (str)

style#

The CSS style template for the button.

Type:

str

class cellpick.app.ui_components.PolygonPreviewItem(*args, **kwargs)#

Bases: QGraphicsItem

A QGraphicsItem for drawing polygon previews with dots at vertices.

Used to show in-progress polygon drawings for landmarks and active regions.

Parameters:
  • points (List[PySide6.QtCore.QPointF] | None)

  • color (Any)

  • pen_w (float)

  • dot_size (float)

  • parent (PySide6.QtWidgets.QGraphicsItem | None)

points#

The polygon vertices.

Type:

List[QPointF]

color#

The color for the polygon outline and vertices.

Type:

Any

pen_w#

The pen width for the outline.

Type:

float

dot_size#

The radius of vertex dots.

Type:

float

points: List[PySide6.QtCore.QPointF]#
color: Any#
pen_w: float#
dot_size: float#
boundingRect()#

Return the bounding rectangle of the polygon.

Return type:

PySide6.QtCore.QRectF

paint(painter, option, widget)#

Paint the polygon outline and vertex dots.

Parameters:
  • painter (PySide6.QtGui.QPainter)

  • option (Any)

  • widget (PySide6.QtWidgets.QWidget | None)

Return type:

None

class cellpick.app.ui_components.ProgressDialog(*args, **kwargs)#

Bases: QDialog

A modal dialog showing a progress bar and status label.

Used for long-running operations like loading shapes.

Parameters:
  • title (str)

  • parent (PySide6.QtWidgets.QWidget | None)

label#

The status text label.

Type:

QLabel

progress#

The progress bar widget.

Type:

QProgressBar

update_progress(value, text=None)#

Update the progress bar value and optionally the status text.

Parameters:
  • value (int) – Progress value (0-100).

  • text (Optional[str], optional) – New status text to display.

Return type:

None

class cellpick.app.ui_components.ClickableLabel(*args, **kwargs)#

Bases: QLabel

A clickable label widget for channel names.

Emits a clicked signal when left-clicked.

Parameters:
  • text (str)

  • parent (PySide6.QtWidgets.QWidget | None)

clicked#

Emitted when the label is left-clicked.

Type:

Signal

mousePressEvent(event)#

Handle mouse press to emit clicked signal.

Parameters:

event (PySide6.QtGui.QMouseEvent)

Return type:

None

class cellpick.app.ui_components.ClickableColorLabel(*args, **kwargs)#

Bases: QLabel

A clickable color swatch widget for channel colors.

Displays a small colored square that emits a clicked signal when left-clicked, used for color picker dialogs.

Parameters:
  • color (Tuple[int, int, int])

  • parent (PySide6.QtWidgets.QWidget | None)

clicked#

Emitted when the label is left-clicked.

Type:

Signal

color#

The current RGB color.

Type:

Tuple[int, int, int]

update_style()#

Update the style sheet with the current color, rounded corners, and border.

Return type:

None

set_color(color)#

Set the color and update the display.

Parameters:

color (Tuple[int, int, int]) – New RGB color.

Return type:

None

mousePressEvent(event)#

Handle mouse press to emit clicked signal.

Parameters:

event (PySide6.QtGui.QMouseEvent)

Return type:

None

class cellpick.app.ui_components.LoadLabelsDialog(*args, **kwargs)#

Bases: QDialog

Dialog for loading cell labels from CSV or SpatialData table.

Provides options to load labels from a CSV file, from a SpatialData table column, or to delete existing labels.

Parameters:
  • spatial_data_loader (Any)

  • parent (PySide6.QtWidgets.QWidget | None)

spatial_data_loader#

Reference to the SpatialData loader for table access.

Type:

Optional[SpatialDataLoader]

selected_source#

The selected source type (‘csv’, ‘spatialdata’, or ‘delete’).

Type:

Optional[str]

csv_path#

Path to the selected CSV file.

Type:

Optional[str]

table_name#

Name of the selected SpatialData table.

Type:

Optional[str]

column_name#

Name of the selected label column.

Type:

Optional[str]

browse_csv()#

Open file dialog to select CSV file.

Return type:

None

on_table_changed(table_name)#

Update column combo when table selection changes.

Parameters:

table_name (str) – Name of the selected table.

Return type:

None

accept()#

Validate selections and accept the dialog.

Return type:

None

cellpick.app.image_viewer#

class cellpick.app.image_viewer.ZoomableGraphicsView(*args, **kwargs)#

Bases: QGraphicsView

A QGraphicsView with mouse wheel zoom and pan functionality.

Provides smooth zooming centered on the mouse cursor and pan navigation via drag mode.

Parameters:

parent (PySide6.QtWidgets.QWidget | None)

scene#

The graphics scene containing all items.

Type:

QGraphicsScene

pixmap_item#

The image pixmap item.

Type:

Optional[QGraphicsPixmapItem]

zoom_factor#

Current zoom level (1.0 = fit to view).

Type:

float

max_zoom#

Maximum allowed zoom factor.

Type:

float

scene: PySide6.QtWidgets.QGraphicsScene#
pixmap_item: PySide6.QtWidgets.QGraphicsPixmapItem | None#
zoom_factor: float#
max_zoom: float#
fit_in_view()#

Fit the image in the view and reset zoom factor.

Return type:

None

set_image(qimage)#

Set a new image and reset the view.

Parameters:

qimage (QImage) – The image to display.

Return type:

None

update_image(qimage)#

Update the displayed image without changing zoom/pan.

Parameters:

qimage (QImage) – The new image to display.

Return type:

None

wheelEvent(event)#

Handle mouse wheel for zooming.

Return type:

None

class cellpick.app.image_viewer.ImageViewer(*args, **kwargs)#

Bases: QWidget

Main image viewer widget with multichannel image display and shape overlays.

Combines a ZoomableGraphicsView with shape management for displaying multichannel microscopy images with polygon overlays for cells, landmarks, and active regions.

Parameters:

state (Any)

state#

Reference to the AppStateManager.

Type:

Any

channels#

List of image channels.

Type:

List[ImageChannel]

composite_image#

The current composite RGB image.

Type:

Optional[np.ndarray]

height#

Image height in pixels.

Type:

Optional[int]

width#

Image width in pixels.

Type:

Optional[int]

shape_items#

Vector items for selected shapes.

Type:

List[QGraphicsPolygonItem]

landmark_items#

Items for landmark polygons.

Type:

List[QGraphicsPolygonItem]

ar_items#

Items for active region polygons.

Type:

List[QGraphicsPolygonItem]

graphics_view#

The main graphics view widget.

Type:

ZoomableGraphicsView

brightness: float#
state: Any#
channels: List[ImageChannel]#
composite_image: numpy.ndarray | None#
gamma: float#
contrast: float#
height: int | None#
width: int | None#
shape_items: List[PySide6.QtWidgets.QGraphicsPolygonItem]#
landmark_items: List[PySide6.QtWidgets.QGraphicsPolygonItem]#
lnd_preview_item: PySide6.QtWidgets.QGraphicsItem | None#
ar_items: List[PySide6.QtWidgets.QGraphicsPolygonItem]#
ar_preview_item: PySide6.QtWidgets.QGraphicsItem | None#
calibration_items: List[PySide6.QtWidgets.QGraphicsPolygonItem]#
graphics_view: ZoomableGraphicsView#
get_pen_scale()#

Get the pen width scale factor based on spatialdata resolution level.

Returns:

Scale factor for pen width (0.25 to 1.0).

Return type:

float

add_channel(image_data, name='', custom_color=None)#

Add a new image channel to the viewer.

Parameters:
  • image_data (np.ndarray) – 2D or 3D array with image data.

  • name (str, optional) – Channel name (default is “”).

  • custom_color (Optional[np.ndarray], optional) – Custom RGB color array (default is None).

Returns:

0 on success, 1 if invalid shape, 2 if dimension mismatch.

Return type:

int

update_display()#

Full display update: recompute composite image AND update shape overlays.

Return type:

None

update_image_only()#

Fast update: only recompute composite image, preserve shape overlays and view.

Return type:

None

set_shapes_visible(visible)#

Show or hide all shape overlays.

Parameters:

visible (bool) – Whether shapes should be visible.

Return type:

None

update_polygon_display()#

Update shape display using hybrid rasterization.

Non-selected shapes are rendered to a single rasterized overlay image. Selected shapes are rendered as vector QGraphicsPolygonItem for crisp display.

Return type:

None

mousePressEvent(event)#
Parameters:

event (Any)

Return type:

None

update_lnd_preview(points)#
Parameters:

points (List[PySide6.QtCore.QPointF])

Return type:

None

add_persistent_lnd(points)#
Parameters:

points (List[PySide6.QtCore.QPointF])

Return type:

None

delete_persistent_lnd(idx)#
Parameters:

idx (int)

Return type:

None

update_ar_preview(points)#
Parameters:

points (List[PySide6.QtCore.QPointF])

Return type:

None

add_persistent_ar(points)#
Parameters:

points (List[PySide6.QtCore.QPointF])

Return type:

None

delete_persistent_ar(idx)#
Parameters:

idx (int)

Return type:

None

add_calibration_item(point, idx)#
Parameters:
  • point (PySide6.QtCore.QPointF)

  • idx (int)

remove_calibration_items()#

Style#