Checking whether an image is part of another I have the following code (slightly modified for simplicity). It checks whether a given image A (the template) is part of another image B. To handle different sizes, image B is scaled as long as a match is found or some minimum/maximum image size is reached.

The naive implementation for this is quite straight forward but I'm not happy with it:


The code within the two while loops is almost identical.
Handling scaling down and scaling up in two different loops is inefficient in a lot of cases (e.g. when the first iteration of the second while loop would find a match but we still need to go through all iterations of the first one).


Can you offer some suggestions on how to improve my code?

double bestMatch = 0;

while (image.width() &gt; MIN_IMAGE_WIDTH) {
   match = match(image, template); // for the sake of simplicity let this return a double
   if (match &gt; bestMatch) {
      bestMatch = match;
   }
   if (match.maxVal &gt;= threshold) {
      foundMatch = true;
      break;
   }
   image = scaleImage(image, 0.9);
}

image = originalImage;
while (image.width() &lt; MAX_IMAGE_WIDTH) {
   match = match(image, template);
   if (match &gt; bestMatch) {
      bestMatch = match;
   }
   if (match.maxVal &gt;= threshold) {
      foundMatch = true;
      break;
   }
   image = scaleImage(image, 1.1);
}

// do something with bestMatch
To answer your second point:

Why not include the foundMatch in the condition of the while?

while (!foundMatch &amp;&amp; image.width() &lt; MAX_IMAGE_WIDTH) {


That way you don't run the second loop at all if a match was found in the first.



Having a couple of duplicate lines isn't a bad thing. It's obvious what the lines do and what the difference is between the 2 loops (1 scaling up, the other scaling down). So at least in my opinion there is nothing wrong with having both loops like this.



I'm actually most surprised that you need to handle scaling at all though. One of the most popular image comparison algorithms these days uses SIFT (Scale invariant feature transform) which, as the name implies is scale invariant.