Reputation: 10041
let's say I have some numpy array (in this case it represents a 100x100 binary image)...
img=np.random.randint(0,2,(100,100)).astype(numpy.uint8)
How best to determine the "average position" of the 1 values in the array? For instance, if therer was a cluster of 1's in the array, I would like to find the center of that cluster.
Upvotes: 3
Views: 4683
Reputation: 1321
I'm seeing you tagged this as numpy
too, so I'd do this:
x = range(0, img.shape[0])
y = range(0, img.shape[1])
(X,Y) = np.meshgrid(x,y)
x_coord = (X*img).sum() / img.sum().astype("float")
y_coord = (Y*img).sum() / img.sum().astype("float")
That wold give you the weighted average center.
If you want this for every cluster of 1's in the image I suggest you use connected components to mask which cluster you're interested in. Might not be a good idea to repeat this process for as many clusters as you want, but rather compute all cluster averages in the same array traversal.
Upvotes: 1