title: How to adjust the threshold for template matching in openCV (java)?
body: <p>I am running template matching using openCV 3.4.7 Android SDK (java).
  The code work almost perfectly; when the template is match, it draws a rectangle on the matching area. The problem is that even when there is no match, it draws a random rectangle. I think that happens because the threshold is not set correctly. If so, can someone please help me out?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>public static void run(String inFile, String templateFile, String outFile,
                      int match_method) {
          Mat img = Imgcodecs.imread(inFile);
          Mat templ = Imgcodecs.imread(templateFile);
  
          // / Create the result matrix
          int result_cols = img.cols() - templ.cols() + 1;
          int result_rows = img.rows() - templ.rows() + 1;
          Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);
  
          // / Do the Matching and Normalize
          Imgproc.matchTemplate(img, templ, result, match_method);
          Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());
  
          // / Localizing the best match with minMaxLoc
          Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
  
          Point matchLoc;
          if (match_method == Imgproc.TM_SQDIFF
                  || match_method == Imgproc.TM_SQDIFF_NORMED) {
              matchLoc = mmr.minLoc;
          } else {
              matchLoc = mmr.maxLoc;
          }
  
          // / Show me what you got
          Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                  matchLoc.y + templ.rows()), new Scalar(0, 0, 128));
  
          // Save the visualized detection.
          System.out.println("Writing " + outFile);
          Imgcodecs.imwrite(outFile, img);
  }
  </code></pre>