Skip to content

Filter Image Using Morphological Gradient

SUMMARY

Filter Image Using Morphological Gradient computes the morphological gradient of an image.

It subtracts the eroded image from the dilated image, both computed with a structuring element of the given kernel_size and kernel_shape, producing a map that highlights object boundaries/outlines. It operates on a binary mask rather than continuous grayscale intensity — use it for a quick edge/outline map from a mask, as opposed to filter_image_using_sobel, which computes gradients directly from grayscale pixel intensity.

Use this Skill when you want to extract object boundaries/outlines from a binary mask using dilation and erosion.

The Skill

python
from telekinesis import pupil

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

Example

Input Image

Input image

Original image of packaging boxes

Filtered Image

Output image

Morphological gradient result — box edges and outlines highlighted, interior regions suppressed

The Code

python
"""Demonstrates filter_image_using_morphological_gradient operation."""

from loguru import logger
import rerun as rr

from telekinesis import pupil, datatypes


def filter_image_using_morphological_gradient_example():
    """Applies filter_image_using_morphological_gradient operation."""
    # ===================== Load Image ==========================================
    image_url = "https://assets.telekinesis.ai/examples/v1/images/cartons_arranged.png"
    image = datatypes.Image.from_url(image_url)

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

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

    # ===================== Visualization  (Optional) ======================
    rr.init("filter_image_using_morphological_gradient_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_gradient_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_gradient.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, 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 gradient 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 object boundaries/outlines highlighted.

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_gradient Skill exposes the structuring element's size and shape, how many times the operation is repeated, and how the image border is handled.

kernel_size

  • Controls: The size of the structuring element used for both the dilation and erosion steps.
  • Units: Pixels
  • Default: 3
  • Increase → thicker edges, more robust to noise
  • Decrease → thinner, finer edge maps
  • Typical range: 3-15

kernel_shape

  • Controls: The geometric shape of the structuring element.
  • Default: "ellipse"
  • Options:
    • ellipse – smooth, isotropic edge detection; good default for natural shapes
    • rectangle – axis-aligned, fast, isotropic along rows/columns
    • cross – thinner than rectangle/ellipse, useful for directional sensitivity and line-like structures
    • diamond – symmetric along diagonals

iterations

  • Controls: How many times the gradient operation is applied sequentially.
  • Units: Count
  • Default: 1
  • Increase → stronger, thicker edge response
  • Decrease → thinner edges
  • 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: Keep kernel_size small (3-5) and iterations=1 for thin, precise boundaries. Only increase either when the input mask is noisy and a thicker, more robust outline is preferable to precision.

Where to Use the Skill

Common pipelines include:

  • Boundary extraction – Derive an outline map from a binary mask produced by a Cornea segmentation Skill
  • Segmentation visualization – Overlay object boundaries on top of the original image for inspection
  • Contour detection preparation – Produce a clean edge map before running a Retina contour detector
  • Feature extraction – Extract boundary features for downstream shape analysis

Alternative Skills

Skillvs. Filter Image Using Morphological Gradient
filter_image_using_sobelComputes derivative-based gradients directly on grayscale intensity, with directional information. Use morphological gradient for binary masks or when robustness to noise matters more than direction.
filter_image_using_laplacianSecond-derivative edge detector for fine detail. Use morphological gradient for thicker, more robust boundaries on binary masks.
filter_image_using_morphological_openRemoves small bright objects/noise instead of extracting boundaries; a common cleanup step before computing the gradient.
filter_image_using_morphological_closeFills small holes/gaps instead of extracting boundaries; a common cleanup step before computing the gradient.

When Not to Use the Skill

Do not use Filter Image Using Morphological Gradient when:

  • You need directional gradient information (use filter_image_using_sobel instead)
  • You need very thin, sub-pixel-precise edges (use a derivative-based detector)
  • The input is a highly textured, non-binary grayscale image (the gradient will highlight all texture, not just object outlines)
  • You need multi-scale edge detection (use filter_image_using_laplacian or a Retina contour detector after thresholding)