Skip to content

Segment Image Using SLIC Superpixel

SUMMARY

Segment Image Using SLIC Superpixel segments an image into compact superpixels using the SLIC algorithm.

Simple Linear Iterative Clustering (SLIC) clusters pixels in color+space using a k-means-like procedure, producing roughly equal-sized, compact (grid-like) superpixels. Compare with segment_image_using_felzenszwalb, which instead produces irregularly-shaped superpixels that adapt more closely to object boundaries — prefer SLIC when you want a predictable, roughly-uniform number/size of superpixels.

Use this Skill when you want to create a predictable, roughly-uniform number of compact superpixels.

The Skill

python
from telekinesis import cornea

segmented_image = cornea.segment_image_using_slic_superpixel(
    image=image,
    num_segments=2,
    compactness=15.0,
    max_iterations=20,
    sigma=0.0,
    enforce_connectivity=True,
    start_label=1,
)
API Reference
Full parameter and return type documentation for segment_image_using_slic_superpixel.
View Reference →

Example

Input Image

Input image

Original image for SLIC superpixel segmentation

Output Image

Output image

Superpixel segmentation using the SLIC algorithm

The Code

python
"""
Demonstrates SLIC superpixel segmentation.
"""

from loguru import logger
import rerun as rr

from telekinesis import cornea, datatypes

def segment_image_using_slic_superpixel_example():
    """Segments an image into compact superpixels using the SLIC algorithm."""
    # ===================== Load Image ==========================================
    image_url = "https://assets.telekinesis.ai/examples/v1/images/nuts.jpg"
    image = datatypes.Image.from_url(url=image_url)

    # ===================== Run Skill ==========================================
    segmented_image = cornea.segment_image_using_slic_superpixel(
        image=image, num_segments=2, compactness=15.0, max_iterations=20,
        sigma=0.0, enforce_connectivity=True, start_label=1
    )

    # ===================== Log ================================================
    logger.success(f"Segmented {image} using the SLIC superpixel algorithm.")
    logger.success(f"Results: {segmented_image}")
    logger.info(f"Segmented image label codes: {segmented_image.label_codes}")
    logger.info(f"Segmented image number of labels: {segmented_image.number_of_labels}")
    logger.info(f"Segmented image shape: {segmented_image.shape}")
    logger.info(f"Segmented image dtype: {segmented_image.dtype}")

    # ===================== Visualization  (Optional) ======================
    rr.init("segment_image_using_slic_superpixel_example", spawn=True)
    datatypes.visualize(image, entity_path="/input_image")
    datatypes.visualize(segmented_image, entity_path="/segmented_image")


if __name__ == "__main__":
    segment_image_using_slic_superpixel_example()

Runnable examples are available in the Telekinesis examples repository.

Follow the README in that repository to set up the environment, run this specific example with:

bash
cd telekinesis-examples
python examples/segmentation/segment_image_using_slic_superpixel.py

Parameter Configuration

KeyTypeDefaultDescription
imagedatatypes.Image | np.ndarrayrequiredInput image to segment, shape (H, W, 3)
num_segmentsdatatypes.Int | int100Approximate number of superpixels to generate. The actual count may differ slightly, especially with enforce_connectivity=True
compactnessdatatypes.Float | float10.0Balances color proximity against spatial proximity when clustering. Higher values weight spatial distance more, producing more square/regular superpixels; lower values let superpixels follow color edges more closely, at the cost of a less regular shape
max_iterationsdatatypes.Int | int10Maximum number of k-means iterations to run
sigmadatatypes.Float | float0.0Standard deviation of the Gaussian smoothing applied to each channel before segmentation. 0.0 disables pre-smoothing
spacinglist[int, int] | NoneNonePixel spacing along each of the 2 image axes, as [spacing_y, spacing_x]. Use for non-square pixels (e.g. anisotropic sensors/scans). None uses uniform spacing
convert_to_labdatatypes.Bool | bool | NoneNoneWhether to convert image to LAB color space before clustering. Only applies to 3-channel images. None uses the algorithm's own default (convert when the image is RGB-like)
enforce_connectivitydatatypes.Bool | boolTrueWhether to postprocess the result so every superpixel is a single spatially-connected region, merging small disconnected fragments into a neighbor
min_size_factordatatypes.Float | float0.5Superpixels smaller than min_size_factor * (image_size / num_segments) are merged into a neighbor when enforce_connectivity=True
max_size_factordatatypes.Float | float3.0Caps how large a merged superpixel may grow, as a multiple of the same expected average size used by min_size_factor
use_slic_zerodatatypes.Bool | boolFalseWhether to use the "SLIC zero" variant, which adapts compactness per cluster instead of using one fixed value
start_labeldatatypes.Int | int1Label assigned to the first superpixel; labels increase sequentially from there. Use 0 for zero-based labels
maskdatatypes.Image | np.ndarray | NoneNoneOptional region-of-interest mask, shape (H, W) matching image. Pixels outside the non-zero region are excluded from segmentation (labeled 0 in the result). None segments the whole image
channel_axisdatatypes.Int | int-1Which axis of image holds the color channels. -1 means the last axis, i.e. shape (H, W, C) — the normal layout for a datatypes.Image

Returns

TypeDescription
datatypes.SegmentationImageA per-pixel label map, shape (H, W), where each pixel's value identifies which superpixel it belongs to (or 0 for pixels excluded by mask). Use .data for the raw label array, .label_codes for the sorted array of unique superpixel ids, .number_of_labels for how many superpixels were found, and .shape/.dtype for its size and label dtype.

Raises

ExceptionCondition
TypeErrorA parameter's value does not match its expected type (see the Parameter Configuration table above)
ConfigurationErrorThe TELEKINESIS_API_KEY environment variable is not set
SerializationErrorThe request input failed to serialize, or the response failed to deserialize
RequestTimeoutErrorThe request to the Cornea service timed out
TransportErrorA network failure occurred before a response was received
ClientErrorThe Cornea service rejected the request due to invalid input, invalid data, or another unexpected 4xx response
AuthenticationErrorThe API key was rejected as invalid or expired
AuthenticationServiceErrorThe authentication service was unavailable
ServerErrorThe Cornea service returned a 5xx or otherwise unexpected error response

How to Tune the Parameters

The segment_image_using_slic_superpixel Skill exposes twelve tunable parameters. The first three (num_segments, compactness, sigma) have the biggest effect on everyday use; the rest fine-tune convergence, connectivity, and input layout.

num_segments

  • Controls: The approximate target number of superpixels.
  • Default: 100
  • Increase → more, smaller superpixels; decrease → fewer, larger superpixels

compactness

  • Controls: The trade-off between spatial regularity and color-edge fidelity during clustering.
  • Default: 10.0
  • Increase → more square/regular superpixels, less attention to color boundaries
  • Decrease → superpixels follow color edges more closely, at the cost of regular shape
  • Typical range: 1.0–40.0

max_iterations

  • Controls: How many k-means iterations the clustering runs.
  • Default: 10
  • Increase → better convergence/quality, slower; decrease → faster, potentially less converged

sigma

  • Controls: Gaussian smoothing applied per-channel before segmentation.
  • Default: 0.0 (no smoothing)
  • Increase → smooths out more noise/fine texture before segmenting

spacing

  • Controls: Per-axis pixel spacing [spacing_y, spacing_x] used when computing spatial distance.
  • Default: None (uniform spacing)
  • Options: Set explicit values only for anisotropic sensors/scans where pixels aren't square

convert_to_lab

  • Controls: Whether pixels are converted to LAB color space before clustering.
  • Default: None
  • Options: None (algorithm default — convert when the image is RGB-like), True (force LAB for more perceptually meaningful color distances), False (cluster in the original color space). Only applies to 3-channel images

enforce_connectivity

  • Controls: Whether disconnected fragments of a superpixel are merged into a neighbor so each label forms one connected region.
  • Default: True
  • Options: True for connected superpixels (recommended for most downstream uses), False to allow disjoint pixels to share a label

min_size_factor

  • Controls: The lower size bound (relative to expected average superpixel size) below which a fragment is merged into a neighbor, when enforce_connectivity=True.
  • Default: 0.5
  • Increase → merges away more small fragments

max_size_factor

  • Controls: The upper bound on merged superpixel size, relative to the same expected average size, when enforce_connectivity=True.
  • Default: 3.0
  • Decrease → caps merged superpixels to a smaller maximum size

use_slic_zero

  • Controls: Whether compactness adapts per cluster (SLIC zero) instead of staying fixed.
  • Default: False
  • Options: True to better handle images mixing flat and highly textured regions, False for standard fixed-compactness SLIC

start_label

  • Controls: The id of the first superpixel; subsequent labels increase sequentially.
  • Default: 1
  • Options: 0 for zero-based labels, 1 (default) for one-based labels

mask

  • Controls: Restricts segmentation to a region of interest; pixels outside the non-zero mask region are labeled 0 instead of assigned to a superpixel.
  • Default: None (segment the whole image)
  • Options: Pass a datatypes.Image/np.ndarray matching image's shape (H, W) to exclude a region

TIP

Recommended tuning order: Set num_segments for roughly the target superpixel count, then adjust compactness to trade off regularity vs. color-edge fidelity. Leave enforce_connectivity=True and the size-factor/iteration/label parameters at their defaults unless you have a specific need (anisotropic pixels, a region-of-interest mask, or textured images where use_slic_zero=True helps).

Where to Use the Skill

Common pipelines include:

  • Superpixel generation – Over-segmenting an image into a predictable, roughly-uniform number of compact regions
  • Object proposal generation – Producing regular candidate regions of known approximate size
  • Preprocessing for filtering – Pairing with filter_segments_by_area, filter_segments_by_color, or filter_segments_by_mask to keep only the superpixels relevant to a downstream task
  • Region-of-interest processing – Using mask to limit segmentation to a specific area of the image rather than post-filtering the whole result

Alternative Skills

Skillvs. Segment Image Using SLIC Superpixel
segment_image_using_felzenszwalbProduces irregularly-shaped superpixels that adapt to object boundaries, instead of uniform, grid-like ones. Use Felzenszwalb when you want superpixels that follow image content; use SLIC when you want a predictable superpixel count/size.
filter_segments_by_areaNot an alternative — a natural next step. Drops superpixels whose pixel area falls outside a chosen range.
filter_segments_by_colorNot an alternative — a natural next step. Drops superpixels whose mean intensity falls outside a chosen range.
filter_segments_by_maskNot an alternative — a natural next step. Keeps only the superpixels that overlap a region-of-interest mask.

When Not to Use the Skill

Do not use Segment Image Using SLIC Superpixel when:

  • You need superpixels that closely follow object boundaries — SLIC's compact, roughly-uniform regions trade boundary fidelity for regularity. Use segment_image_using_felzenszwalb instead.
  • You need irregularly-shaped, boundary-respecting regions — high compactness values in particular push superpixels toward square, grid-like shapes.

TIP

If you only need superpixels within a specific region of the image, pass that region as mask instead of segmenting the whole image and filtering afterward — pixels outside the mask are labeled 0 directly, avoiding wasted computation on irrelevant regions.