Skip to content

Filter Image Using Morphological Close

SUMMARY

Filter Image Using Morphological Close applies morphological closing (dilation followed by erosion).

Closing fills small holes and gaps, useful for connecting nearby components while preserving overall shape. This operation first expands objects to close gaps, then shrinks them back to approximately their original size. It's particularly effective for filling holes in objects and connecting closely spaced components without significantly changing their boundaries.

Use this Skill when you want to fill holes and connect nearby objects while maintaining size.

The Skill

python
from telekinesis import pupil

filtered_image = pupil.filter_image_using_morphological_close(
    image=image,
    kernel_size=5,
    kernel_shape="ellipse",
    iterations=1,
    border_type="default",
)

API Reference

Example

Input Image

Input image

Original image with holes and gaps

Filtered Image

Output image

Closed image - holes filled, objects connected

The Code

python
from telekinesis import pupil
from datatypes import io
import pathlib
from loguru import logger

DATA_DIR = pathlib.Path("path/to/telekinesis-data")

# Load image
filepath = str(DATA_DIR / "images" / "nuts_scattered.jpg")
image = io.load_image(filepath=filepath, as_binary=True)
logger.success(f"Loaded image from {filepath}")

# Apply close morphological operation
filtered_image = pupil.filter_image_using_morphological_close(
    image=image,
    kernel_size=5,
    kernel_shape="ellipse",
    iterations=5,
    border_type="default",
)

# Access results
filtered_image_np = filtered_image.to_numpy()
logger.success("Applied close morphological operation. Output image shape: {}", filtered_image_np.shape)

The Explanation of the Code

The code begins by importing the necessary modules: pupil for image processing operations, io for data handling, pathlib for path management, and loguru for logging.

python
from telekinesis import pupil
from datatypes import io
import pathlib
from loguru import logger

Next, a binary mask is loaded from a .jpg file using the io.load_image function. The image is loaded as binary using as_binary=True, which creates a binary mask suitable for morphological operations.

python
DATA_DIR = pathlib.Path("path/to/telekinesis-data")

# Load the binary image
filepath = str(DATA_DIR / "images" / "nuts_scattered.jpg")
image = io.load_image(filepath=filepath, as_binary=True)

The main operation uses the filter_image_using_morphological_close Skill from the pupil module. This Skill applies morphological closing (dilation followed by erosion) to fill small holes and connect nearby components while preserving overall shape. The parameters can be tuned to control hole size, kernel shape, iteration strength, and border handling depending on the characteristics of the input image.

python
filtered_image = pupil.filter_image_using_morphological_close(
    image=image,
    kernel_size=5,
    kernel_shape="ellipse",
    iterations=5,
    border_type="default",
)

Finally, the filtered image is converted to a NumPy array using to_numpy() for further processing, visualization, or downstream tasks.

python
filtered_image_np = filtered_image.to_numpy()
logger.success(f"Output image shape: {filtered_image_np.shape}")

This operation is particularly useful in robotics and vision pipelines for hole filling, mask refinement, object completion, and segmentation cleanup, where connecting nearby components without expanding object boundaries is required.

Running the Example

Runnable examples are available in the Telekinesis examples repository. Follow the README in that repository to set up the environment. Once set up, you can run this specific example with:

bash
cd telekinesis-examples
python examples/pupil_examples.py --example filter_image_using_morphological_close

How to Tune the Parameters

The filter_image_using_morphological_close Skill has 4 parameters that control hole filling and object connection:

kernel_size (default: 3): Controls the size of the structuring element used for closing.

  • Units: Pixels
  • Increase to fill larger holes and connect more distant objects; Decrease for less aggressive filling
  • Typical range: 3–15 (min: 3, max: 15)
  • Use 3–5 for small holes, 5–9 for moderate gaps, 9–15 for large holes

kernel_shape (default: ellipse): Defines the geometric shape of the structuring element used for dilation and erosion.

  • Options:
    • ellipse - Produces smooth, isotropic closing (recommended for most cases)
    • rectangle - Axis-aligned operations
    • cross - Directional effects
    • diamond - Approximates circular morphology with sharper diagonal influence
  • Use ellipse for most cases

iterations (default: 1):

  • The number of times closing is applied
  • Units: Count
  • Increase to fill progressively larger holes; Decrease for less aggressive filling
  • Typical range: 1–10 (min: 1, max: 10)
  • Each iteration compounds the effect

border_type (default: default): Determines how image borders are handled when the structuring element extends beyond the image boundary.

  • Options:
    • default - Uses reflect 101 padding (recommended)
    • constant - Pads borders with a constant value (typically zero)
    • replicate - Repeats the nearest edge pixel
    • reflect - Mirrors the border pixels
    • reflect 101 - Mirror reflection without repeating the border pixel
  • Use default or reflect for most cases

TIP

Best practice: Closing is ideal for filling holes in segmented objects. Choose kernel_size based on the size of holes you want to fill—the kernel should be slightly larger than the holes.

Where to Use the Skill in a Pipeline

Morphological Closing is commonly used in the following pipelines:

  • Object segmentation cleanup - Fill holes in detected objects
  • Region connection - Connect nearby regions into single objects
  • Contour smoothing - Smooth concave boundaries
  • Mask refinement - Clean up segmentation masks
  • Feature completion - Complete partially detected features

Related skills to build such a pipeline:

  • filter_image_using_morphological_open: Remove noise
  • filter_image_using_morphological_dilate: Expand objects
  • filter_image_using_morphological_erode: Shrink objects

Alternative Skills

Skillvs. Morphological Closing
filter_image_using_morphological_openOpening removes noise, closing fills holes. Use opening to remove small objects, closing to fill small holes.
filter_image_using_morphological_dilateDilation only expands. Use closing when you want to fill holes without permanently expanding objects.

When Not to Use the Skill

Do not use Morphological Closing when:

  • You want to remove noise (Use opening instead)
  • You want to separate touching objects (Use erosion or opening)
  • Holes are actually important features (Don't fill them)
  • You need to preserve all boundary details (Closing will smooth boundaries)