Skip to content

Filter Image Using Morphological Blackhat

SUMMARY

Filter Image Using Morphological Blackhat applies the morphological black-hat transform to an image.

It subtracts the original image from its morphological closing, isolating whatever the closing filled in: dark features/details smaller than the structuring element defined by kernel_size/kernel_shape. This highlights small dark defects, scratches, or holes on an otherwise uniform surface. It is the complementary operation to filter_image_using_morphological_tophat, which highlights small bright features instead.

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

The Skill

python
from telekinesis import pupil

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

Example

Input Image

Input image

Original image of machined metal parts (gears, shafts, pins) on a light background

Filtered Image

Output image

Black-hat result — fine dark details (grooves, edges, teeth gaps) isolated against the surrounding surface

The Code

python
"""Demonstrates filter_image_using_morphological_blackhat operation."""

from loguru import logger
import rerun as rr

from telekinesis import pupil, datatypes


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

    # ===================== Run Skill ==========================================
    filtered_image = pupil.filter_image_using_morphological_blackhat(
        image=image,
        kernel_size=15,
        kernel_shape="ellipse",
        iterations=2,
        border_type="default",
    )

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

    # ===================== Visualization  (Optional) ======================
    rr.init("filter_image_using_morphological_blackhat_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_blackhat_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_blackhat.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 closing 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 black-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 dark 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_blackhat Skill mirrors top-hat: kernel_size sets the ceiling on what counts as a "small" dark feature—anything smaller than the structuring element is extracted, anything larger is treated as background and suppressed.

kernel_size

  • Controls: The size of the structuring element used for the closing step that black-hat subtracts the original from.
  • Units: Pixels
  • Default: 3
  • Increase → extracts larger dark features (cracks, holes)
  • Decrease → extracts only the finest dark details
  • Typical range: 3-15

kernel_shape

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

iterations

  • Controls: How many times the underlying closing operation is applied before subtracting.
  • Units: Count
  • Default: 1
  • Increase → isolates progressively larger dark features
  • Decrease → preserves only the smallest dark 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: Black-hat is the complement of top-hat — use it for dark holes, cracks, or defects on a bright background. Set kernel_size to just above the size of the features you want to extract so the surrounding bright surface is not picked up.

Where to Use the Skill

Common pipelines include:

  • Crack/hole detection – Detect fine cracks or pores in bright, otherwise-uniform surfaces
  • Defect detection – Find dark surface defects on machined or manufactured parts
  • Dark feature enhancement – Enhance dark detail obscured by a bright, varying background
  • Preprocessing for thresholding – Isolate dark features before segmentation or measurement

Alternative Skills

Skillvs. Filter Image Using Morphological Blackhat
filter_image_using_morphological_tophatExtracts small bright features instead. Use black-hat for dark features on a bright background, top-hat for bright features on a dark background.
filter_image_using_morphological_closeProduces the closed image that black-hat subtracts the original from; use directly when you want the filled/closed result 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 Blackhat when:

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