Skip to content

Segment Image Using Yen Threshold

SUMMARY

Segment Image Using Yen Threshold segments an image using a single global threshold chosen by Yen's method.

Yen's method automatically picks the threshold that maximizes an entropy-based measure of separation between the two resulting classes — another parameter-free global threshold, like Otsu's, but based on a different statistical criterion that can perform better on histograms with unequal-sized foreground/background regions.

Use this Skill when you want to automatically segment an image whose intensity histogram isn't cleanly bimodal, without specifying a threshold value.

The Skill

python
from telekinesis import cornea

segmented_image = cornea.segment_image_using_yen_threshold(image=image)
API Reference
Full parameter and return type documentation for segment_image_using_yen_threshold.
View Reference →

Example

Input Image

Input image

Original image for Yen threshold segmentation

Output Image

Output image

Segmented image using automatic Yen threshold

The Code

python
"""
Demonstrates Yen threshold segmentation.
"""

from loguru import logger
import rerun as rr

from telekinesis import cornea, datatypes

def segment_image_using_yen_threshold_example():
    """Applies Yen's method to segment the image based on intensity histograms."""
    # ===================== Load Image ==========================================
    image_url = "https://assets.telekinesis.ai/examples/v1/images/bolts_and_%20nuts_white_bg.jpg"
    image = datatypes.Image.from_url(url=image_url)

    # ===================== Run Skill ==========================================
    segmented_image = cornea.segment_image_using_yen_threshold(image=image)

    # ===================== Log ================================================
    logger.success(f"Segmented {image} using Yen's threshold method.")
    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_yen_threshold_example", spawn=True)
    datatypes.visualize(image, entity_path="/input_image")
    datatypes.visualize(segmented_image, entity_path="/segmented_image")


if __name__ == "__main__":
    segment_image_using_yen_threshold_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_yen_threshold.py

Parameter Configuration

KeyTypeDefaultDescription
imagedatatypes.Image | np.ndarrayrequiredInput image to segment, shape (H, W) or (H, W, 3)

Returns

TypeDescription
datatypes.SegmentationImageA per-pixel label map, shape (H, W), where pixels above and below the automatically-chosen threshold are assigned distinct labels. Use .data for the raw label array, .label_codes for the sorted array of unique ids present, .number_of_labels for how many distinct labels 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

segment_image_using_yen_threshold takes only image — there is nothing to tune. The threshold is chosen automatically by maximizing an entropy-based separation criterion between the two resulting classes, which is the point of the Skill: a parameter-free method that can perform better than segment_image_using_otsu_threshold when the foreground and background regions are unequal in size.

If you need explicit control over the threshold value instead of an automatic choice, use segment_image_using_threshold.

Where to Use the Skill

Common pipelines include:

  • Quick automatic segmentation – When a threshold value isn't known in advance and doesn't need to be tuned by hand
  • Unequal foreground/background segmentation – Images where the object of interest occupies a much smaller or larger area than the background, where Otsu's variance-based split can perform worse
  • Document processing – Separating text or print from a uniform background
  • Preprocessing – Producing a first-pass mask ahead of filter_segments_by_area/filter_segments_by_color

Alternative Skills

Skillvs. Segment Image Using Yen Threshold
segment_image_using_otsu_thresholdAlso automatic and parameter-free, using variance minimization instead of an entropy-based criterion. Try both on the same image — Yen tends to help when the histogram isn't cleanly bimodal or the classes are unequal in size.
segment_image_using_thresholdUses a manually chosen threshold instead of an automatic one. Prefer manual threshold when you already know a good value for your setup.
segment_image_using_adaptive_thresholdComputes a threshold per pixel from its local neighborhood. Prefer this when lighting varies across the image, since Yen picks one global value.
segment_image_using_local_thresholdAlso a local/neighborhood method, simpler than adaptive threshold. Same trade-off vs. Yen as adaptive threshold.
segment_image_using_laplacian_thresholdThresholds on local edge strength rather than raw intensity. Use it to isolate textured or detailed regions instead of bright/dark ones.

When Not to Use the Skill

Do not use Segment Image Using Yen Threshold when:

TIP

Yen and Otsu are both parameter-free and take only image, so they're cheap to try side by side on the same image — run both and keep whichever separates foreground from background more cleanly.