title: How to find the dominant color in images using Python?
body: <p>I am trying to find top 2 colors from my image to process them accordingly
  For example if image has blue and white i apply one rule, if it is green and red i apply some other rule.I am trying below code which work for some and not for all.</p>
  
  <p>Main goal : every image has top 2 dominant visible color as shown below  and i need to get those color.</p>
  
  <p>Expected result : </p>
  
  <p>image1 : blue and yellow shade</p>
  
  <p>image2 : green shade and blue shade</p>
  
  <p>code :</p>
  
  <pre><code>from PIL import Image
  
  import numpy as np
  import scipy
  import scipy.misc
  import scipy.cluster
  
  NUM_CLUSTERS = 5
  
  print('reading image')
  im = Image.open("captcha_green.jpg")   # optional, to reduce time
  ar = np.asarray(im)
  shape = ar.shape
  ar = ar.reshape(scipy.product(shape[:2]), shape[2]).astype(float)
  
  print('find clus')
  codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
  print ('cluster centres:\n', codes)
  
  vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
  counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences
  
  index_max = scipy.argmax(counts)                    # find most frequent
  peak = codes[index_max]
  colour = ''.join(chr(int(c)) for c in peak).encode("utf-8").hex()
  print ('most frequent is %s (#%s)' % (peak, colour))
  </code></pre>
  
  <p>For this image </p>
  
  <p><a href="https://i.stack.imgur.com/F4BOG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/F4BOG.jpg" alt="enter image description here"></a></p>
  
  <p>I am getting most <code>frequent is [  1.84704063   1.59035213 252.29132127] (#0101c3bc)</code>  As per this link <a href="https://www.w3schools.com/colors/colors_picker.asp?color=80ced6" rel="nofollow noreferrer">https://www.w3schools.com/colors/colors_picker.asp?color=80ced6</a> It is detecting blue that is true.</p>
  
  <p>For green image : instead of green shade it is detecting light pink</p>
  
  <p><a href="https://i.stack.imgur.com/SrCTu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SrCTu.jpg" alt="enter image description here"></a></p>
  
  <p>Detected coloe : <code>most frequent is [142.17271615 234.99711606 144.77187718] (#c28ec3aac290)</code> this is wrong prediction</p>