Distance Transform

The example in this section is present in the source under mahotas/demos/distance.py.

We start with an image, a black&white image that is mostly black except for two white spots:

import numpy as np
import mahotas

f = np.ones((256,256), bool)
f[200:,240:] = False
f[128:144,32:48] = False

(Source code, png, hires.png, pdf)

_images/distance-1.png

There is a simple distance() function which computes the distance map:

import mahotas
dmap = mahotas.distance(f)

Now dmap[y,x] contains the squared euclidean distance of the pixel (y,x) to the nearest black pixel in f. If f[y,x] == True, then dmap[y,x] == 0.

import pylab as p
import numpy as np
import mahotas

f = np.ones((256,256), bool)
f[200:,240:] = False
f[128:144,32:48] = False
# f is basically True with the exception of two islands: one in the lower-right
# corner, another, middle-left

dmap = mahotas.distance(f)
p.imshow(dmap)
p.show()

(Source code, png, hires.png, pdf)

_images/distance.png

API Documentation

A package for computer vision in Python.

mahotas.distance(bw, metric='euclidean2')

Computes the distance transform of image bw:

dmap[i,j] = min_{i', j'} { (i-i')**2 + (j-j')**2 | bw[i', j'] }
Parameters :

bw : 2d-ndarray

Black & White image

metric : str, optional

one of ‘euclidean2’ (default) or ‘euclidean’

Returns :

dmap : ndarray

distance map

Table Of Contents

Previous topic

Thresholding

Next topic

Labeled Image Functions

This Page