private void centerTemplate(int startX, int startY, int endX, int endY, int granularity) {
    int stepX = bestfit.getTemplate().getWidth() / granularity;
    int stepY = bestfit.getTemplate().getHeight() / granularity;
    // System.out.println("stepX = " + stepX + ": stepY = " + stepY);

    double maxsim = -1;
    int simi = -1, simj = -1;
    for (int iCount = startX; iCount <= endX; iCount += stepX) {
      for (int jCount = startY; jCount <= endY; jCount += stepY) {
        double currsim = 1.0 - templateXOR(img, iCount, jCount, bestfit.getTemplate(), false);
        // System.out.println(i + ":" + j + ":" + currsim);
        if (maxsim == -1 || maxsim < currsim) {
          maxsim = currsim;
          simi = iCount;
          simj = jCount;
        }
      }
    }

    // System.out.println("--- maxsim = " + maxsim + ":"
    // + simi + ":" + simj);
    if (maxsim > 0.5) {
      if (stepX >= 4) { // up to an accuracy of 2 pixels
        centerTemplate(
            Math.max(simi - stepX / 2, 0),
            Math.max(simj - stepY / 2, 0),
            Math.min(simi + stepX / 2, img.getWidth()),
            Math.min(simj + stepY / 2, img.getHeight()),
            granularity * 2);
      } else {
        bestfit.setX(simi);
        bestfit.setY(simj);
        bestfit.setSim(maxsim);
      }
    }
  }
 private void fillTemplate(
     Gray8Image templateimg, double outerdiamX, double innerdiamX, double aspect) {
   double centerX = templateimg.getWidth() / 2;
   double centerY = templateimg.getHeight() / 2;
   double outerrad = outerdiamX / 2;
   double innerrad = innerdiamX / 2;
   for (int wCount = 0; wCount < templateimg.getWidth(); wCount++) {
     for (int hCount = 0; hCount < templateimg.getHeight(); hCount++) {
       double dist =
           Math.sqrt(
               (wCount - centerX) * (wCount - centerX)
                   + (hCount - centerY) / aspect * (hCount - centerY) / aspect);
       if (dist <= outerrad && dist > innerrad) {
         templateimg.putBlack(wCount, hCount);
       } else {
         templateimg.putWhite(wCount, hCount);
       }
     }
   }
 }