Friday, November 14, 2025
HomeLanguagesMahotas – Distance from binary image

Mahotas – Distance from binary image

In this article we will see how we can obtain distance map of binary image in mahotas. A distance transform, also known as distance map or distance field, is a derived representation of a digital image. The choice of the term depends on the point of view on the object in question: whether the initial image is transformed into another representation, or it is simply endowed with an additional map or field. 
In order to do this we will use mahotas.distance method 
 

Syntax : mahotas.distance(img)
Argument : It takes image object which should be binary as argument
Return : It returns image object 
 

Note : Input image should be binary image it can be labeled as well, image should be filtered or should be loaded as grey to make it binary
In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this
 

image = image[:, :, 0]

Example 1: 
 

Python3




# importing required libraries
import mahotas as mh
import numpy as np
from pylab import imshow, show
  
# creating region
# numpy.ndarray
regions = np.zeros((10, 10), bool)
  
# setting 1 value to the region
regions[:3, :3] = 1
regions[6:, 6:] = 1
  
# getting labeled function
labeled, nr_objects = mh.label(regions)
  
# showing the image with interpolation = 'nearest'
print("Image")
imshow(labeled, interpolation ='nearest')
show()
 
# getting distance map
dmap = mahotas.distance(labeled)
 
# showing image
print("Distance Map")
imshow(dmap)
show()


Output : 
 

Example 2: 
 

Python3




# importing required libraries
import numpy as np
import mahotas
from pylab import imshow, show
  
# loading image
img = mahotas.imread('dog_image.png')
    
# filtering the image
img = img[:, :, 0]
     
# setting gaussian filter
gaussian = mahotas.gaussian_filter(img, 15)
  
# setting threshold value
gaussian = (gaussian > gaussian.mean())
  
# creating a labeled image
labeled, n_nucleus = mahotas.label(gaussian)
  
 
print("Image")
# showing the gaussian filter
imshow(labeled)
show()
 
 
# getting distance map
dmap = mahotas.distance(labeled)
 
# showing image
print("Distance Map")
imshow(dmap)
show()


Output : 
 

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32399 POSTS0 COMMENTS
Milvus
95 POSTS0 COMMENTS
Nango Kala
6765 POSTS0 COMMENTS
Nicole Veronica
11917 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11984 POSTS0 COMMENTS
Shaida Kate Naidoo
6889 POSTS0 COMMENTS
Ted Musemwa
7142 POSTS0 COMMENTS
Thapelo Manthata
6837 POSTS0 COMMENTS
Umr Jansen
6840 POSTS0 COMMENTS