Wilmar van Ommeren - 2 years ago 170
Python Question

# Find center coordinates of regions in a 3d numpy array

I have a large numpy 3d array (10000, 3, 3). in which I would like to find the center coordinates of each region (clusters with the same number). Each sub-array can have 1, 2, 3 or 4 regions.

A subset of my array is:

``````largearray= array([[[1, 0, 0],
[0, 0, 2],
[3, 0, 2]],

[[0, 0, 4],
[0, 0, 4],
[0, 0, 4]],

[[5, 0, 0],
[5, 0, 6],
[0, 6, 6]],

[[7, 0, 8],
[0, 0, 0],
[9, 0,10]]])
``````

The output that I would like would be the location of the subarray and the x and y coordinates representing the centers:

``````#output:
array([[ 0., 0., 0.],
[ 0., 1.5, 2.],
[ 0., 2., 0.],
[ 1., 1.,  2.],
[ 2., 0.5,  0.],
[ 2., 1.66666667, 1.66666667],
[ 3., 0., 0.],
[ 3., 0., 2.],
[ 3., 2., 0.],
[ 3., 2., 2.]])
``````

I am open to other outputs, but something like this would be awesome!

Are you looking for this?

``````n_clusters = 10
for i in range(1, n_clusters + 1):
matches = np.transpose((largearray == i).nonzero())
print "The center of cluster {} is at {}".format(i, np.mean(matches, axis=0))
``````
``````The center of cluster 1 is at [ 0.  0.  0.]
The center of cluster 2 is at [ 0.   1.5  2. ]
The center of cluster 3 is at [ 0.  2.  0.]
The center of cluster 4 is at [ 1.  1.  2.]
The center of cluster 5 is at [ 2.   0.5  0. ]
The center of cluster 6 is at [ 2.          1.66666667  1.66666667]
The center of cluster 7 is at [ 3.  0.  0.]
The center of cluster 8 is at [ 3.  0.  2.]
The center of cluster 9 is at [ 3.  2.  0.]
The center of cluster 10 is at [ 3.  2.  2.]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download