Skip to content

Filter Image Using Morphological Tophat

SUMMARY

Filter Image Using Morphological Tophat applies the morphological top-hat transform to an image.

It subtracts the morphologically opened image from the original, isolating whatever the opening removed: bright features/details smaller than the structuring element defined by kernel_size/kernel_shape. This highlights small bright defects or fine bright detail sitting on top of a larger, more uniform background. The complementary operation is filter_image_using_morphological_blackhat, which highlights small dark features instead.

Use this Skill when you want to extract or enhance small bright features against a larger background.

The Skill

python
from telekinesis import pupil

filtered_image = pupil.filter_image_using_morphological_tophat(
    image=image,
    kernel_size=3,
    kernel_shape="ellipse",
    iterations=5,
    border_type="default",
)
API Reference
Full parameter and return type documentation for filter_image_using_morphological_tophat.
View Reference →

Example

Input Image

Input image

Original close-up image of a keyhole plate with fine scratches

Filtered Image

Output image

Top-hat result — fine scratches and the keyhole outline isolated as small bright features against the metal surface

The Code

python
"""Demonstrates filter_image_using_morphological_tophat operation."""

from loguru import logger
import rerun as rr

from telekinesis import pupil, datatypes


def filter_image_using_morphological_tophat_example():
    """Applies filter_image_using_morphological_tophat operation."""
    # ===================== Load Image ==========================================
    image_url = "https://assets.telekinesis.ai/examples/v1/images/keyhole.jpg"
    image = datatypes.Image.from_url(image_url)

    # ===================== Run Skill ==========================================
    filtered_image = pupil.filter_image_using_morphological_tophat(
        image=image,
        kernel_size=3,
        kernel_shape="ellipse",
        iterations=5,
        border_type="default",
    )

    # ===================== Log ================================================
    logger.success(f"Applied filter_image_using_morphological_tophat on {image}")
    logger.success(f"Result: {filtered_image}")

    # ===================== Visualization  (Optional) ======================
    rr.init("filter_image_using_morphological_tophat_example", spawn=True)
    datatypes.visualize(image, entity_path="1-Original")
    datatypes.visualize(filtered_image, entity_path="2-Filtered")

if __name__ == "__main__":
    filter_image_using_morphological_tophat_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/image_processing/filter_image_using_morphological_tophat.py

Parameter Configuration

KeyTypeDefaultDescription
imagedatatypes.Image | np.ndarrayrequiredThe input image to process, shape (H, W). Recommended to use a binary image/mask
kernel_sizedatatypes.Int | int3The size of the structuring element used for the opening step, in pixels
kernel_shapedatatypes.String | str"ellipse"The shape of the structuring element: ellipse, rectangle, cross, or diamond
iterationsdatatypes.Int | int1The number of times the top-hat operation is applied
border_typedatatypes.String | str"default"The border handling mode: default, constant, replicate, reflect, or reflect 101
border_valuedatatypes.Float | float | int0.0The fill value used only when border_type is "constant"

Returns

TypeDescription
datatypes.ImageSame shape as image, with small bright features highlighted against the background.

Raises

ExceptionCondition
TypeErrorimage, kernel_size, kernel_shape, iterations, border_type, or border_value has an invalid type
ValueErrorkernel_shape or border_type is not one of the supported options
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 Pupil service timed out
TransportErrorA network failure occurred before a response was received
ClientErrorThe Pupil 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 Pupil service returned a 5xx or otherwise unexpected error response

How to Tune the Parameters

The filter_image_using_morphological_tophat Skill is driven primarily by kernel_size: features smaller than the structuring element are extracted, larger ones are suppressed along with the background.

kernel_size

  • Controls: The size of the structuring element used for the opening step that top-hat subtracts from the original.
  • Units: Pixels
  • Default: 3
  • Increase → extracts larger bright features relative to the background
  • Decrease → extracts only the finest bright details
  • Typical range: 3-15

kernel_shape

  • Controls: The geometric shape of the structuring element.
  • Default: "ellipse"
  • Options:
    • ellipse – smooth, isotropic extraction of bright features
    • rectangle – axis-aligned, directional along rows/columns
    • cross – emphasizes line-like structures
    • diamond – symmetric along diagonals

iterations

  • Controls: How many times the underlying opening operation is applied before subtracting.
  • Units: Count
  • Default: 1
  • Increase → removes progressively larger background structures, isolating larger bright features
  • Decrease → preserves only the smallest bright details
  • Typical range: 1-10

border_type

  • Controls: How pixels are synthesized when the structuring element extends past the image boundary.
  • Default: "default"
  • Options:
    • default – reflect 101 padding, suitable for most cases
    • constant – pads with border_value
    • replicate – repeats the nearest edge pixel
    • reflect – mirrors border pixels without repeating the edge
    • reflect 101 – mirror reflection without repeating the edge pixel

TIP

Best practice: Set kernel_size larger than the features you want to extract but smaller than the background variations you want to remove. Combine with iterations to push the effective structuring element size further without picking an overly large kernel_size outright.

Where to Use the Skill

Common pipelines include:

  • Background correction – Remove uneven illumination before thresholding
  • Small object/defect detection – Detect particles, scratches, or bright surface defects
  • Detail enhancement – Enhance fine bright detail obscured by a varying background
  • Preprocessing for thresholding – Normalize background brightness before segmentation

Alternative Skills

Skillvs. Filter Image Using Morphological Tophat
filter_image_using_morphological_blackhatExtracts small dark features instead. Use top-hat for bright features on a dark/uniform background, black-hat for dark features on a bright background.
filter_image_using_morphological_openProduces the opened image that top-hat subtracts from the original; use directly when you want the background/shape estimate rather than the residual.
enhance_image_using_claheEnhances local contrast adaptively rather than isolating features smaller than a fixed structuring element; use for general contrast correction instead of feature isolation.

When Not to Use the Skill

Do not use Filter Image Using Morphological Tophat when:

  • You want to extract dark features instead (use filter_image_using_morphological_blackhat)
  • The features of interest are larger than the background variations (top-hat will suppress them along with the background)
  • You need to preserve overall background/illumination information (top-hat discards it by design)
  • The background is already uniform (top-hat adds no value over the raw image)