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
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",
)Example
Input Image

Original image of packaging boxes
Filtered Image

Morphological gradient result — box edges and outlines highlighted, interior regions suppressed
The Code
"""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:
cd telekinesis-examples
python examples/image_processing/filter_image_using_morphological_gradient.pyParameter Configuration
| Key | Type | Default | Description |
|---|---|---|---|
image | datatypes.Image | np.ndarray | required | The input image to process, shape (H, W). Recommended to use a binary image/mask |
kernel_size | datatypes.Int | int | 3 | The size of the structuring element, in pixels |
kernel_shape | datatypes.String | str | "ellipse" | The shape of the structuring element: ellipse, rectangle, cross, or diamond |
iterations | datatypes.Int | int | 1 | The number of times the gradient operation is applied |
border_type | datatypes.String | str | "default" | The border handling mode: default, constant, replicate, reflect, or reflect 101 |
border_value | datatypes.Float | float | int | 0.0 | The fill value used only when border_type is "constant" |
Returns
| Type | Description |
|---|---|
datatypes.Image | Same shape as image, with object boundaries/outlines highlighted. |
Raises
| Exception | Condition |
|---|---|
TypeError | image, kernel_size, kernel_shape, iterations, border_type, or border_value has an invalid type |
ValueError | kernel_shape or border_type is not one of the supported options |
ConfigurationError | The TELEKINESIS_API_KEY environment variable is not set |
SerializationError | The request input failed to serialize, or the response failed to deserialize |
RequestTimeoutError | The request to the Pupil service timed out |
TransportError | A network failure occurred before a response was received |
ClientError | The Pupil service rejected the request due to invalid input, invalid data, or another unexpected 4xx response |
AuthenticationError | The API key was rejected as invalid or expired |
AuthenticationServiceError | The authentication service was unavailable |
ServerError | The 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 shapesrectangle– axis-aligned, fast, isotropic along rows/columnscross– thinner than rectangle/ellipse, useful for directional sensitivity and line-like structuresdiamond– 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 casesconstant– pads withborder_valuereplicate– repeats the nearest edge pixelreflect– mirrors border pixels without repeating the edgereflect 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
| Skill | vs. Filter Image Using Morphological Gradient |
|---|---|
| filter_image_using_sobel | Computes 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_laplacian | Second-derivative edge detector for fine detail. Use morphological gradient for thicker, more robust boundaries on binary masks. |
| filter_image_using_morphological_open | Removes small bright objects/noise instead of extracting boundaries; a common cleanup step before computing the gradient. |
| filter_image_using_morphological_close | Fills 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_sobelinstead) - 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_laplacianor a Retina contour detector after thresholding)

