Image.distance_transform#

Image.distance_transform(invert: bool = False, norm: str = 'L2', h: int = 1) → Any[source]#

Distance transform

Parameters:
  • invert (bool, optional) – consider inverted image, defaults to False

  • norm (str, optional) – distance metric: ‘L1’ or ‘L2’ [default]

  • h (int, optional) – half width of window, defaults to 1

Returns:

distance transform of image

Return type:

Image

Compute the distance transform. For each zero input pixel, compute its distance to the nearest non-zero input pixel. Any non-zero value counts as foreground, so the input need not be binary or have the values 0 and 255.

Examples

>>> from machinevisiontoolbox import Image
>>> import numpy as np
>>> pixels = np.zeros((5,5), dtype=np.uint8)
>>> pixels[2, 1:3] = 1
>>> img = Image(pixels)
>>> img.distance_transform().print(precision=3)
   2.324 1.910 1.910 2.324 2.739
   1.369 0.955 0.955 1.369 2.324
   0.955 0.000 0.000 0.955 1.910
   1.369 0.955 0.955 1.369 2.324
   2.324 1.910 1.910 2.324 2.739
>>> img.distance_transform(norm="L1").print()
   3.00 2.00 2.00 3.00 4.00
   2.00 1.00 1.00 2.00 3.00
   1.00 0.00 0.00 1.00 2.00
   2.00 1.00 1.00 2.00 3.00
   3.00 2.00 2.00 3.00 4.00

Note

  • The output image is the same size as the input image.

  • Distance is computed using a sliding window and is an approximation of true distance.

  • For non-zero input pixels the corresponding output pixels are set to zero.

  • The signed-distance function is image.distance_transform() - image.distance_transform(invert=True)

Changed in version 2.5.0: Any non-zero pixel is treated as foreground. Previously the image was inverted as 255 - x, which only worked for images whose pixels were 0 or 255. For any other values there was no zero pixel left, and the result was about 65000 everywhere.

References

Important

Uses OpenCV function cv2.distanceTransform which accepts single-channel, CV_8U images.