title: Template Matching maximizing equal pixels
body: <p>I am trying to find a template in an image and I am using OpenCV for that. The problem is that the TM_SQDIFF function is not exactly what I need and it fails in some cases, for example:</p>
  
  <p>Template:</p>
  
  <p><a href="https://i.stack.imgur.com/6vdvt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6vdvt.png" alt="Template"></a></p>
  
  <p>Image:</p>
  
  <p><a href="https://i.stack.imgur.com/cj8lb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cj8lb.png" alt="Image"></a></p>
  
  <p>Result using SQDIFF:</p>
  
  <p><a href="https://i.stack.imgur.com/5zO6D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5zO6D.png" alt="enter image description here"></a></p>
  
  <p>I want the template to match the bottom right image, because it has more elements that are equal to the template than the result that SQDIFF shows.</p>
  
  <p>What I need seems to be a simpler than the SQDIFF, but I couldn't find a way to do it. Is it possible to do that using OpenCV or another tool in Python?</p>
  
  <p>Ideally I also want to be able to use a mask, because some of the templates are not rectangular.</p>