Find centroid in a 2d array (list of lists)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jul 2008
Posts: 39
Reputation: tillaart36 is an unknown quantity at this point 
Solved Threads: 0
tillaart36 tillaart36 is offline Offline
Light Poster

Find centroid in a 2d array (list of lists)

 
0
  #1
Feb 19th, 2009
Hi,

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

  1. grid = [[0, 0, 0, 0, 0],
  2. [0, 1, 1, 1, 0],
  3. [0, 1, 1, 0, 0],
  4. [0, 1, 1, 1, 0],
  5. [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.
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Find centroid in a 2d array (list of lists)

 
0
  #2
Feb 22nd, 2009
You mean the center of mass?

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

  1. >>> def findCOM(grid):
  2. Mx = 0
  3. My = 0
  4. mass = 0
  5.  
  6. for i in range(len(grid)):
  7. for j in range(len(grid[i])):
  8. if grid[i][j]:
  9. Mx += j
  10. My += i
  11. mass += 1
  12. COM = (float(Mx)/mass , float(My)/mass)
  13. return COM
  14.  
  15. >>> grid = [[0, 0, 0, 0, 0],
  16. [0, 1, 1, 1, 0],
  17. [0, 1, 1, 0, 0],
  18. [0, 1, 1, 1, 0],
  19. [0, 0, 0 ,0, 0]]
  20.  
  21. >>> findCOM(grid)
  22. (1.875, 2.0)
  23. >>>

Jeff
Reply With Quote Quick reply to this message  
Join Date: Jun 2009
Posts: 2
Reputation: no_spam_for_dan is an unknown quantity at this point 
Solved Threads: 0
no_spam_for_dan no_spam_for_dan is offline Offline
Newbie Poster

Re: Find centroid in a 2d array (list of lists)

 
0
  #3
Jun 18th, 2009
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)
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 1001 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC