title: Find centroid and color value of circles in image
body: <p>I have images with eight blue and eight red circles. <br>
  I want to find the center position (<code>(x, y)</code> in pixels) of each circle and I also want to know whether the circle is red or blue. 
  The circles can have a slight variation in diameter.</p>
  
  <p><a href="https://i.stack.imgur.com/v9ydr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9ydr.png" alt="This is what I&#39;m trying to process"></a><br>
  It feels like this would not be so hard to solve, but it's to hard for me ...</p>
  
  <p>I tried using <code>OpenCV</code> and Template Matching by following a <a href="https://docs.opencv.org/trunk/d4/dc6/tutorial_py_template_matching.html" rel="nofollow noreferrer">tutorial</a>. It finds all the circles <strong>but I don't know how to pinpoint the center or pick the circle-color</strong>. <br>
  It also seems to draw a lot more than 1 rectangle per circle. </p>
  
  <p><a href="https://i.stack.imgur.com/8fpGN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8fpGN.png" alt="Circles identified using Template Matching"></a></p>
  
  <pre><code>img_rgb = cv2.imread('images/img.png')
  img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
  template = cv2.imread('red.png',0)
  w, h = template.shape[::-1]
  res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
  threshold = 0.66
  loc = np.where( res &gt;= threshold)
  for pt in zip(*loc[::-1]):
      cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 1)
  </code></pre>
  
  <p>I also gave <code>Hough Circles</code> a try. But without any result at all. Maybe my circles are too small to be true circles, with the pixels showing. </p>
  
  <p>Is Template Matching the right approach, even if I don't get it to work all the way, or can it be done more easily another way? </p>
  
  <p>Any help would be much appreciated.<br>
  Thanks Martin</p>