0

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.

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by no_spam_for_dan
0

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

0

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)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.