-1

What does it mean when an array is used as another array's index? This is the code I saw, and I don't understand

res = center[label.flatten()]

center and label come from the opencv method kmeans.

ret, label, center = cv2.kmeans(flat, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center = cv2.cvtColor(np.uint8([center]), cv2.COLOR_LAB2BGR)
center = center[0]
MigfibOri
  • 73
  • 7
  • 1
    Are you absolutely sure that both `center` and `label.flatten()` are arrays? Could you show us their initialization? – pilu Apr 13 '18 at 11:41
  • 1
    https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html – YSelf Apr 13 '18 at 11:41
  • @pilu center and label come from the opencv method, kmeans. I've added the line where they are initialized to that it's clearer – MigfibOri Apr 13 '18 at 11:48

2 Answers2

2

You can get multiple elements by index using an np.ndarray. In your case label.flatten() is an array of the indices of the the array center that you need. For example if center is an array of k-means centroids, then this operation selects some of those centers.

A minimal example:

a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]

print(list(a[b])) # Prints [1, 5, 5]

You can also check this question.

pilu
  • 720
  • 5
  • 16
0

I also worked with this algorithm of K means.

1) In centers you would have k points. 2) In labels you would have k clustered numbered array. i.e for k = 3 label = [0,1,0,2,0,1 ... ] something like this.

what res = center[label.flatten()] it does is, it paste center point in label array instead of just 0,1,2

For example if centers were [123,212,41] then this res = center[label.flatten()] will make label array look like [123,212,123,41,123,212 ....]

Bilal Nadeem
  • 19
  • 1
  • 5