Hi,

my question is how I can find the centroid of group of cells that share the same value. Say I have this:

grid = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0 ,0, 0]]

I need to get the centroid in x and y = (1.875, 2)

I tried to iterate over all values and when this is 1 store all the x and y coordinates but im stucked as how to actually get the centroid of these points.

You mean the center of mass?

Well, do it like the physicists do: Sum(moments) / Sum(masses):

>>> def findCOM(grid):
    Mx = 0
    My = 0
    mass = 0

    for i in range(len(grid)):
       for j in range(len(grid[i])):
         if grid[i][j]:
            Mx += j
            My += i
            mass += 1
    COM = (float(Mx)/mass , float(My)/mass)
    return COM

>>> grid = [[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0 ,0, 0]]

>>> findCOM(grid)
(1.875, 2.0)
>>>

Jeff

You could just take the average using pylab:

>>> import pylab

>>> grid = pylab.array[[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0 ,0, 0]]

>>> ( pylab.average(pylab.array(grid.nonzero())[1,:]), pylab.average(pylab.array(grid.nonzero())[0,:]) )
(1.875, 2.0)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.