'Explanation of Python's bwlabel,regionprops & centroid functions

In Matlab there is a documentation about how to use bwlabel, region props, and centroid functions. I am wondering how we can use the same things in Python: Let's say in Matlab, we have:

[L,num] = bwlabel(img)

where L is the integer map, num tells us how many objects exist in the image, and ima is a binary image.

If we defined a function phi(x,y) (for exemple a circular function, or any other shape), and we defined phi = 0 is the contour of this function, phi > 0 is inside the geometrical shape, phi < 0 is outside the shape.

This small Matlab program allows to obtains the centroid of circular shape defined by phi function.

shape = Phi > = 0
[labeled, Num] = bwlabel(shape)
s = regionprops(shape, 'centroid')
for i = 1:Num
    props = [i, (s.centroid)]
end 

I am trying to do the same things in python code, however I got centroids greater than the domain of my figure. It is definitely an error in the code:

import numpy
from skimage import measure
import pandas

xstart, xend = 0.0, 8.0
ystart, yend = 0.0, 8.0
N = 50
x = numpy.linspace(xstart, xend, N)
y = numpy.linspace(ystart, yend, N)
X,Y = numpy.meshgrid(x,y)
xc, yc = 3.6, 4.2
phi = numpy.sqrt((X-xc)**2 + (Y-yc)**2) - r
shape = phi > = 0

labels = measure.label(shape, connectivity=None)
props = measure.regionprops_table(labels, properties=['centroid'])
properties = pandas.DataFrame(props)
print(properties.head())


Solution 1:[1]

There are two issues with your code:

  1. shape = phi >= 0 creates an object with a hole in it, rather than a circular object. Instead, do shape = phi <= 0.

  2. measure.regionprops_table() has no idea of your coordinate system. All you pass in is the image. It returns the centroid in pixel units. The MATLAB code does exactly the same thing! You can obtain the centroid in your coordinate system using numpy.interp:

    centroid_x = numpy.interp(props['centroid-1'], numpy.arange(0, shape.shape[1]), x)
    centroid_y = numpy.interp(props['centroid-0'], numpy.arange(0, shape.shape[0]), y)
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cris Luengo