Cv2 kmeans with initial labels


I’m trying to use cv2.kmenas with initial values, but I don’t succeed in passing the right parameters.

After reading the documentation I’ve assumed that parameter centers is the same as the centers obtained as a return from calling the function.

Thus I do ret, label, center_obtingut = cv2.kmeans(Z,16,None,criteria, 1,cv2.KMEANS_RANDOM_CENTERS) and the funtion runs without problem.

Then I want to use it again with the centers obtained (center_obtingut), and I do ret, label, center = cv2.kmeans(Z,16,None,criteria, 1,cv2.KMEANS_USE_INITIAL_LABELS, centers=center_obtingut) but I get the error:

error: OpenCV(4.7.0) /home/abuild/rpmbuild/BUILD/opencv-4.7.0/modules/core/src/kmeans.cpp:259: error: (-215:Assertion failed) (unsigned)<int>(i) < (unsigned)K in function 'kmeans'.

What am I doing wrong?

please look at the kmeans() docs again

you can set initial labels, but NOT centers
(which internally are calculated from the labels as last step of kmeans())

Oh! I see.
I was really surprised to see bestLabels as parameter, but now I understand why the flag cv2.KMEANS_USE_INITIAL_LABELS does not include the name centers. So, when you use kmeans with this flag, you need to provide the initial labels.

With this way of working, I assume that the parameter centers is also needed with the initial_labels to compute the first attempt.

Finally, if you had an image already clustered and then you add a new element in the image and you want to use the previous clustering, the best option is to use Initial_Label with PP_Centers.

Thanks a lot berak for the answer, I should read the documentation more thoroughly.