943,918 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 3511
  • Python RSS
Feb 19th, 2009
0

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

Expand Post »
Hi,

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

Python Syntax (Toggle Plain Text)
  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.
Reputation Points: 12
Solved Threads: 0
Light Poster
tillaart36 is offline Offline
41 posts
since Jul 2008
Feb 22nd, 2009
0

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

You mean the center of mass?

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

Python Syntax (Toggle Plain Text)
  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
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Jun 18th, 2009
0

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

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)
Reputation Points: 10
Solved Threads: 0
Newbie Poster
no_spam_for_dan is offline Offline
2 posts
since Jun 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Start remote file with associated application
Next Thread in Python Forum Timeline: Printing words that begin within capital letters





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC