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
from telekinesis import cornea
filtered_image = cornea.filter_segments_by_area(
image=image,
labels=labels,
min_area=10000,
max_area=100000,
)Example
Input Image

Original image with superpixels
Output Image

Filtered image - only segments within area range shown
The Code
"""
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:
cd telekinesis-examples
python examples/segmentation/filter_segments_by_area.pyParameter Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
image | datatypes.Image | np.ndarray | required | The original image the segments were computed from, shape (H, W, 3) |
labels | datatypes.SegmentationImage | np.ndarray | required | The label map to filter, typically the output of another Cornea segmentation skill, shape (H, W) |
min_area | datatypes.Int | int | 20 | Minimum segment area, in pixels, required to keep a segment. Segments with fewer pixels are removed (relabeled as background) |
max_area | datatypes.Int | int | 1000 | Maximum segment area, in pixels, allowed to keep a segment. Segments with more pixels are removed |
Returns
| Type | Description |
|---|---|
datatypes.SegmentationImage | A 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
| Exception | Condition |
|---|---|
TypeError | A parameter's value does not match its expected type (see the Parameter Configuration table above) |
ValueError | min_area is negative, or min_area is not less than max_area |
ConfigurationError | The TELEKINESIS_API_KEY environment variable is not set |
SerializationError | The request input failed to serialize, the response was not returned as an Arrow stream, or the response failed to deserialize |
RequestTimeoutError | The request to the Cornea service timed out |
TransportError | A network failure occurred before a response was received |
ClientError | The Cornea service rejected the request due to invalid or malformed input (HTTP 400/422), an unrecognized endpoint (HTTP 404), or another unexpected 4xx response |
AuthenticationError | The API key was rejected as invalid or expired (HTTP 401) |
AuthenticationServiceError | The authentication service returned an invalid response, was temporarily unavailable, or timed out (HTTP 502/503/504) |
ServerError | The 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_felzenszwalborsegment_image_using_slic_superpixelbefore 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
| Skill | vs. Filter Segments By Area |
|---|---|
| filter_segments_by_color | Filters 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_mask | Filters 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_felzenszwalb | A primary segmenter that produces the labels this Skill filters. Run it first. |
| segment_image_using_slic_superpixel | Another 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_colorinstead - The distinguishing property is spatial location, not size - use
filter_segments_by_maskinstead - You don't yet have a
labelsmap - run a segmentation skill such assegment_image_using_felzenszwalborsegment_image_using_slic_superpixelfirst
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.