How to perform distance transformation on a given image in OpenCV Python?

Distance transformation is a morphological operation that calculates the distance from every pixel of the foreground to the nearest pixel of the background in a binary image. OpenCV provides the cv2.distanceTransform() method to perform this operation.

Syntax

cv2.distanceTransform(src, distanceType, maskSize)

Parameters

This method accepts the following parameters ?

  • src 8-bit, single-channel (binary) source image.

  • distanceType Type of distance calculation (cv2.DIST_L1, cv2.DIST_L2, cv2.DIST_C).

  • maskSize Size of the distance transform mask (3, 5, or cv2.DIST_MASK_PRECISE).

Steps to Perform Distance Transform

  1. Import required libraries (OpenCV, NumPy, Matplotlib)
  2. Read the input image using cv2.imread()
  3. Convert BGR image to grayscale using cv2.cvtColor()
  4. Apply thresholding to create a binary image
  5. Apply distance transform using cv2.distanceTransform()
  6. Normalize the result for visualization
  7. Display the distance transformed image

Basic Distance Transform Example

This example demonstrates basic distance transformation using L2 (Euclidean) distance ?

import cv2
import numpy as np

# Create a sample binary image
image = np.zeros((100, 100), dtype=np.uint8)
cv2.rectangle(image, (20, 20), (80, 80), 255, -1)
cv2.circle(image, (50, 50), 15, 0, -1)

# Apply distance transform
dist_transform = cv2.distanceTransform(image, cv2.DIST_L2, 3)

# Normalize for visualization
cv2.normalize(dist_transform, dist_transform, 0, 255, cv2.NORM_MINMAX)
dist_transform = np.uint8(dist_transform)

# Display results
cv2.imshow('Original Binary Image', image)
cv2.imshow('Distance Transform', dist_transform)
cv2.waitKey(0)
cv2.destroyAllWindows()

Comparing Different Distance Types

This example compares various distance calculation methods ?

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Create a sample binary image
image = np.zeros((100, 100), dtype=np.uint8)
cv2.rectangle(image, (30, 30), (70, 70), 255, -1)

# Apply different distance transforms
dist_L1 = cv2.distanceTransform(image, cv2.DIST_L1, 3)
dist_L2 = cv2.distanceTransform(image, cv2.DIST_L2, 3)
dist_C = cv2.distanceTransform(image, cv2.DIST_C, 3)

# Normalize all transforms
transforms = [dist_L1, dist_L2, dist_C]
names = ['Manhattan (L1)', 'Euclidean (L2)', 'Chessboard (C)']

for i, dist in enumerate(transforms):
    cv2.normalize(dist, dist, 0, 1.0, cv2.NORM_MINMAX)

# Visualize results
fig, axes = plt.subplots(1, 4, figsize=(12, 3))
axes[0].imshow(image, cmap='gray')
axes[0].set_title('Original Binary')
axes[0].axis('off')

for i, (dist, name) in enumerate(zip(transforms, names)):
    axes[i+1].imshow(dist, cmap='hot')
    axes[i+1].set_title(name)
    axes[i+1].axis('off')

plt.tight_layout()
plt.show()

Distance Types Comparison

Distance Type Formula Characteristics
DIST_L1 (Manhattan) |x1-x2| + |y1-y2| Diamond-shaped distance
DIST_L2 (Euclidean) ?[(x1-x2)² + (y1-y2)²] Circular distance (most natural)
DIST_C (Chessboard) max(|x1-x2|, |y1-y2|) Square-shaped distance

Common Applications

  • Morphological operations Watershed segmentation, skeletonization

  • Object analysis Finding object centers, measuring thickness

  • Image processing Erosion/dilation with variable structuring elements

Conclusion

Distance transformation is essential for morphological operations and object analysis. Use DIST_L2 for most applications as it provides the most natural circular distance measurement. Different distance types produce different shape patterns in the output.

Updated on: 2026-03-26T22:56:54+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements