Skip to content

Filter Segments By Area

SUMMARY

Filter Segments By Area removes segments from an existing label map whose pixel area falls outside a given range.

It is a post-processing step, not a standalone segmenter: it takes the labels produced by a prior segmentation call (e.g. segment_image_using_felzenszwalb or segment_image_using_slic_superpixel) together with the original image, counts each segment's pixels, and relabels as background any segment whose area is below min_area or above max_area. Use it to discard tiny noise segments and/or implausibly large ones, such as a background region that merged with an object.

Use this Skill when you want to discard segments from a label map that are too small or too large, based on their pixel area.

The Skill

python
from telekinesis import cornea

filtered_image = cornea.filter_segments_by_area(
    image=image,
    labels=labels,
    min_area=10000,
    max_area=100000,
)
API Reference
Full parameter and return type documentation for filter_segments_by_area.
View Reference →

Example

Input Image

Input image

Original image with superpixels

Output Image

Output image

Filtered image - only segments within area range shown

The Code

python
"""
Demonstrates filtering superpixels by area.
"""

from loguru import logger
import rerun as rr
import rerun.blueprint as rrb

from telekinesis import cornea, datatypes

def filter_segments_by_area_example():
    """Filters superpixels based on area."""
    # ===================== Load Image ==========================================
    image_url = "https://assets.telekinesis.ai/examples/v1/images/eggs_carton.jpg"
    image = datatypes.Image.from_url(url=image_url)

    # ===================== Run Skill ==========================================
    superpixel_segmentation_image = cornea.segment_image_using_felzenszwalb(
        image=image, 
        scale=500,
        sigma=1,
        min_size=200
    )

    filtered_image = cornea.filter_segments_by_area(
        image=image, labels=superpixel_segmentation_image,
        min_area=10000, max_area=100000
    )

    # ===================== Log ================================================
    logger.success(f"Filtered {image} superpixels by area.")
    logger.success(f"Results: {filtered_image}")
    logger.info(f"Filtered image label codes: {filtered_image.label_codes}")
    logger.info(f"Filtered image number of labels: {filtered_image.number_of_labels}")
    logger.info(f"Filtered image shape: {filtered_image.shape}")
    logger.info(f"Filtered image dtype: {filtered_image.dtype}")

    # ===================== Visualization  (Optional) ======================
    rr.init("filter_segments_by_area_example", spawn=True)
    blueprint = rrb.Horizontal(
        rrb.Spatial2DView(origin="/input_image", name="Input"),
        rrb.Spatial2DView(origin="/filtered_image", name="Output"),
    )
    rr.send_blueprint(blueprint)
    datatypes.visualize(image, entity_path="/input_image")
    datatypes.visualize(filtered_image, entity_path="/filtered_image")


if __name__ == "__main__":
    filter_segments_by_area_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/filter_segments_by_area.py

Parameter Configuration

ParameterTypeDefaultDescription
imagedatatypes.Image | np.ndarrayrequiredThe original image the segments were computed from, shape (H, W, 3)
labelsdatatypes.SegmentationImage | np.ndarrayrequiredThe label map to filter, typically the output of another Cornea segmentation skill, shape (H, W)
min_areadatatypes.Int | int20Minimum segment area, in pixels, required to keep a segment. Segments with fewer pixels are removed (relabeled as background)
max_areadatatypes.Int | int1000Maximum segment area, in pixels, allowed to keep a segment. Segments with more pixels are removed

Returns

TypeDescription
datatypes.SegmentationImageA per-pixel label map, shape (H, W), with the out-of-range segments removed. Use .data for the raw label array, .label_codes for the sorted array of unique ids remaining, .number_of_labels for how many segments survived the filter, 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)
ValueErrormin_area is negative, or min_area is not less than max_area
ConfigurationErrorThe TELEKINESIS_API_KEY environment variable is not set
SerializationErrorThe request input failed to serialize, the response was not returned as an Arrow stream, 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 or malformed input (HTTP 400/422), an unrecognized endpoint (HTTP 404), or another unexpected 4xx response
AuthenticationErrorThe API key was rejected as invalid or expired (HTTP 401)
AuthenticationServiceErrorThe authentication service returned an invalid response, was temporarily unavailable, or timed out (HTTP 502/503/504)
ServerErrorThe Cornea service returned a 5xx or otherwise unexpected error response

How to Tune the Parameters

The filter_segments_by_area Skill exposes two thresholds that together define the pixel-area range a segment must fall within to survive the filter.

min_area

  • Controls: The minimum pixel count a segment needs to be kept.
  • Units: Pixels
  • Default: 20
  • Increase → filters out more small, noisy segments
  • Decrease → keeps smaller segments that would otherwise be dropped
  • Typical range: depends on image resolution and expected object size

max_area

  • Controls: The maximum pixel count a segment may have to be kept.
  • Units: Pixels
  • Default: 1000
  • Decrease → filters out implausibly large segments, e.g. a background region that swallowed an object
  • Increase → keeps larger segments that would otherwise be dropped
  • Typical range: depends on image resolution and expected object size

TIP

Inspect the label_codes/number_of_labels of the unfiltered labels first (e.g. compute each segment's pixel count) to pick min_area/max_area values that bracket your objects of interest rather than guessing.

Where to Use the Skill

Common pipelines include:

  • Noise removal – Drop small spurious segments left over from segment_image_using_felzenszwalb or segment_image_using_slic_superpixel before further processing
  • Background rejection – Remove an oversized segment where the background merged with part of an object
  • Object counting – Keep only segments within the expected size range of the objects being counted
  • Pipeline cleanup – Narrow a superpixel map down to plausible object candidates before color or mask filtering

Alternative Skills

Skillvs. Filter Segments By Area
filter_segments_by_colorFilters the same kind of label map by each segment's mean pixel intensity instead of its pixel count. Often chained after or before this filter.
filter_segments_by_maskFilters the label map by spatial overlap with a region-of-interest mask instead of size. Use together to combine size and location constraints.
segment_image_using_felzenszwalbA primary segmenter that produces the labels this Skill filters. Run it first.
segment_image_using_slic_superpixelAnother primary segmenter whose output labels this Skill can filter. Run it first.

When Not to Use the Skill

Do not use Filter Segments By Area when:

  • You need to keep every segment regardless of size - filtering by area will drop anything outside [min_area, max_area]
  • The distinguishing property is color, not size - use filter_segments_by_color instead
  • The distinguishing property is spatial location, not size - use filter_segments_by_mask instead
  • You don't yet have a labels map - run a segmentation skill such as segment_image_using_felzenszwalb or segment_image_using_slic_superpixel first

TIP

Because min_area/max_area are absolute pixel counts, re-tune them whenever the input image resolution changes significantly, otherwise the same thresholds will filter a smaller or larger fraction of segments than intended.