arXiv:2608.24738cs.CVAug 2026

Manuscript Offprint

arXiv:2608.24738

TorchMorph: CUDA-accelerated Morphological Transforms

Kai Zhao

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

Abstract

Morphological transforms are long-standing tools for shape and mask processing, but the de-facto reference implementation in the Python ecosystem, i.e. scipy.ndimage, is CPU-only, single-array, and therefore unusable inside a GPU training loop without an expensive device-to-host round trip. GPU vision libraries built on PyTorch cover a narrow subset of these operators, typically restricted to two spatial dimensions and flat structuring elements. We present TORCHMORPH, a lightweight PyTorch extension that closes this gap. TORCHMORPH exposes 22 public operators covering binary morphology, greyscale morphology, exact and approximate distance transforms, and entropy-regularised optimal transport, all implemented as fused CUDA kernels that operate directly on (B, C, Spatial...) CUDA tensors with up to eight spatial dimensions. The API deliberately mirrors scipy.ndimage argument-for-argument, including border modes, structuring-element origins and pre-allocated outputs, so that existing pipelines port with a change of import. We describe the layered architecture and the kernel designs behind each operator family. Against single-threaded CPU references, batched execution reaches up to 1.1×1031.1 \times 10^3 times the throughput of scipy.ndimage on greyscale morphology and up to 350×350 \times on exact Euclidean distance transforms, while the Sinkhorn solver runs up to 42×42 \times faster than POT. Binary and chamfer operators reproduce their SciPy counterparts exactly, and every float-valued operator agrees with the CPU reference to within 1.8×10−61.8 \times 10^{-6} absolute error. TORCHMORPH is released under the MIT licence at https://intcomp.github.io/tm.

Keywords: Morphological Transforms, Distance Transform, Optimal Transport, CUDA, PyTorch, Open Source

1 Introduction

Mathematical morphology supplies some of the oldest and most widely used primitives in image analysis [1, 2]. Erosion, dilation and their compositions underpin denoising, shape decomposition and connected-component post-processing, while the distance transform, an erosion by a parabolic structuring function, underpins skeletonisation and watershed seeding [3, 4], boundary-aware losses [5] and Hausdorff-distance surrogates [6]. In the Python ecosystem these operators are canonically provided by scipy.ndimage [7], whose semantics for border modes, structuring-element origins and connectivity conventions have become the de-facto standard that downstream libraries are expected to reproduce.

That reference implementation was designed for a world in which images live in host memory as NumPy arrays [8]. In modern AI-native imaging pipelines, images are represented differently in three specific ways. First, data live on the GPU as PyTorch tensors [9], so every call into scipy.ndimage forces a device-to-host copy, a single-threaded CPU computation, and a copy back. Second, data arrive in batches: a training step processes tens of volumes at once, and a per-image Python loop over a CPU routine serialises what is naturally an embarrassingly parallel workload. Third, the interesting regime is often three- or four-dimensional (volumetric time series, multi-channel tomography), where the CPU cost of a morphological sweep grows with the product of all spatial extents.

The obvious response is to use a GPU vision library, but that runs into a coverage problem. Kornia [10] provides differentiable 2-D morphology, but not N-dimensional operators, the full scipy.ndimage border-mode matrix, or an exact Euclidean distance transform; cuCIM [11] offers GPU morphology through CuPy, an interoperability layer rather than native torch.Tensor operators; MONAI [12] delegates several morphological post-processing steps back to SciPy or CuPy; and OpenCV [13] and scikit-image [14] are host-side and two-dimensional in their fast paths. Entropic optimal transport, increasingly used as a shape- and histogram-comparison loss [15, 16], lives in yet another stack [17, 18]. A practitioner who wants batched GPU morphology, an exact distance transform and a differentiable transport distance must therefore assemble three libraries with three tensor conventions. Table 1 summarises the resulting coverage gap.

TORCHMORPH closes that gap in one place. It brings these operators into the PyTorch tensor world as native, batch-parallel CUDA kernels: 22 public operators spanning binary and greyscale morphology, exact and approximate distance transforms, and entropy-regularised optimal transport. Every one accepts (B, C, Spatial...) CUDA tensors of spatial rank up to eight, and mirrors

Source code: https://github.com/intcomp/torchmorph

GPUTorchBatchN-DSem.EDTOT
scipy.ndimage [7]✕✕✕✓✓✓✕
scikit-image [14]✕✕✕✓~✓✕
OpenCV [13]~✕✕✕✕✓✕
Kornia [10]✓✓✓✕✕~✕
cuCIM [11]✓✕✕✕~✓✕
MONAI [12]✓✓~✕✕~✕
POT [17]✓✓✓✕✕✕✓
TORCHMORPH✓✓✓✓✓✓✓

Table 1: Coverage of the capabilities TORCHMORPH targets. ✓ = supported, ~ = partial or indirect, ✕ = not supported. Torch = operates on torch.Tensor natively; Batch = a single call over a leading batch dimension rather than a Python loop; N-D = more than three spatial dimensions; Sem. = matches scipy.ndimage border modes, structuring-element origins and iteration conventions; EDT = exact Euclidean distance transform.

its scipy.ndimage counterpart in name, argument order, defaults and boundary behaviour, so porting is a change of import rather than a rewrite, and 3-D and 4-D data are first-class rather than special cases. The operators are fused rather than assembled from generic tensor primitives: one launch per call, with structuring-element geometry resolved on the host, an interior fast path that removes per-axis boundary tests, and CUDA-graph replay for the transport iterations. The library depends only on PyTorch and a CUDA toolchain, is validated element-wise against SciPy and POT, and is released under the MIT licence. Section 2 describes the transforms it covers and the design behind them; Section 3 reports its numerical agreement and throughput against the CPU reference.