title: Python + OpenCV color segmentation using Kmeans
body: <p>I am trying to apply the kmeans from opencv in order to segment the image in HSV color space.</p>
  
  <pre><code>def leftOffset(src, p_countours):
      height, width, size = src.shape
  
      p_width = width/p_countours
      o_left = src[0:height, 0:p_width]
  
      HSV_img = cv2.cvtColor(o_left, cv2.COLOR_BGR2HSV)
      hue = HSV_img[0]
      hue = np.float32(HSV_img)
  
      # Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
      criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
  
      # Set flags (Just to avoid line break in the code)
      flags = cv2.KMEANS_RANDOM_CENTERS
  
      # Apply KMeans
      compactness,labels,centers = cv2.kmeans(hue,2,criteria,10,flags)
  
      centers = np.uint8(centers)
      res = centers[labels.flatten()]
      res2 = res.reshape((hue.shape))
      cv2.imshow("o_left", hue)
      cv2.waitKey(0)
  </code></pre>
  
  <p>I am now able to apply the kmeans algorithm to the HSVImage[0] with K=2, and how can I get a image like threshold according to the result?</p>
  
  <p>Thanks</p>
  
  <p>To clarify the question:
  I have color-based captchas, and I want to segment each digits.</p>
  
  <p>The image is like<a href="https://i.stack.imgur.com/7zovC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7zovC.jpg" alt="6"></a></p>
  
  <p><a href="https://i.stack.imgur.com/EWP8g.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EWP8g.jpg" alt="1"></a></p>
  
  <p>I am going to use k-means method to find out the dominant color and segment the digits inside.</p>