Stephen
Stephen

Reputation: 21

Python opencv cv2.KMEANS_RANDOM_CENTERS

Based on the cv2.kmeans function, I have written a function "F(Image)" with "label" as output.

ret,label,center=cv2.kmeans(Image,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

The output of F(Image), "label", is later used for other image processing.

However, I need to run F(Image) for numerous images. I noticed that the labels are different if I ran, say, F(Image1) and F(Image2) consecutively versus F(Image1) and F(Image2) separately.

My suspicion is that every time cv2.KMEANS_RANDOM_CENTERS is ran, it starts at a different random number.

Without going into the source code of cv2.KMEANS_RANDOM_CENTERS, is there any way to ensure that the labels are the same every time I run the code? Or run F(Image1) and F(Image2) as in they are ran separately.

Upvotes: 1

Views: 4570

Answers (2)

MigfibOri
MigfibOri

Reputation: 73

The method only keeps the best labels after each iteration. So if the number of iterations you set is high enough, let's say cv2.kmeans(Image,K,None,criteria,100,cv2.KMEANS_RANDOM_CENTERS), the output result would be similar.

Upvotes: 1

ZdaR
ZdaR

Reputation: 22954

cv2.kmeans() takes 2 type of flags: cv2.KMEANS_PP_CENTERS and cv2.KMEANS_RANDOM_CENTERS.

cv2.KMEANS_RANDOM_CENTERS:

With this flag enabled, the method always starts with a random set of initial samples, and tries to converge from there depending upon your TermCirteria.

Pros:

  • Saves computation Time.

Cons:

  • Doesn't guarantee same labels for the exact same image.

cv2.KMEANS_PP_CENTERS:

With this flag enabled, the method first iterates the whole image to determine the probable centers and then starts to converge.

Pros:

  • Would yield optimum and consistent results for same input image

Cons:

  • Takes extra computation time for iterating all the pixels and determining probable samples.

Note: I have also read about another flag cv::KMEANS_USE_INITIAL_LABELS, using which you can pass custom samples, which are used by the method to converge, But in the documentation linked, that flag is not mentioned, Not Sure if it has been deprecated or the documentation is not updated.

Upvotes: 2

Related Questions