title: OpenCV Template Match Similar Object
body: <p>I am currently trying to use OpenCV template matching function to detect all similar objects in a given image using a template. However, I am not getting all objects (which are blood cells) to be detected even though they are pretty much similar and identical. I have been searching around on Internet for solution but haven't get any.</p>
  
  <p>The following is my code:</p>
  
  <pre><code>cv::Mat ref = cv::imread("c:\\image.jpg");
  cv::Mat tpl = cv::imread("c:\\template.jpg");
  
  cv::Mat gref, gtpl;
  cv::cvtColor(ref, gref, CV_BGR2GRAY);
  cv::cvtColor(tpl, gtpl, CV_BGR2GRAY);
  
  cv::Mat res(ref.rows-tpl.rows+1, ref.cols-tpl.cols+1, CV_32FC1);
  cv::matchTemplate(gref, gtpl, res, CV_TM_CCOEFF_NORMED);
  cv::threshold(res, res, 0.8, 1., CV_THRESH_TOZERO);
  
  while (true)
  {
      double minval, maxval, threshold = 0.8;
      cv::Point minloc, maxloc;
      cv::minMaxLoc(res, &amp;minval, &amp;maxval, &amp;minloc, &amp;maxloc);
  
      if (maxval &gt;= threshold)
      {
          cv::rectangle(
              ref,
              maxloc,
              cv::Point(maxloc.x + tpl.cols, maxloc.y + tpl.rows),
              CV_RGB(0,255,0), 2
          );
          cv::floodFill(res, maxloc, cv::Scalar(0), 0, cv::Scalar(.1), cv::Scalar(1.));
      }
      else
          break;
  }
  
  cv::imshow("reference", ref);
  </code></pre>
  
  <p>These are the result and image used:</p>
  
  <p>Given Image</p>
  
  <p><a href="https://i.stack.imgur.com/ZA208.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZA208.jpg" alt="Given Image"></a></p>
  
  <p>Template</p>
  
  <p><a href="https://i.stack.imgur.com/qfrVE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qfrVE.jpg" alt="Template"></a></p>
  
  <p>Result with higher threshold setting (0.8/0.8)</p>
  
  <p><a href="https://i.stack.imgur.com/Dbj3W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dbj3W.png" alt="Result"></a></p>
  
  <p>Result with lower threshold settings (0.6/0.3)</p>
  
  <p><a href="https://i.stack.imgur.com/Q9JrV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q9JrV.png" alt="enter image description here"></a></p>
  
  <p>I am pretty new to template matching, is there a way to make all objects in the image get detected?</p>
  
  <p>I need the template matching to detect the cells in some more complicated image as well.</p>
  
  <p><a href="https://i.stack.imgur.com/Bsh9X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bsh9X.jpg" alt="enter image description here"></a></p>