3
\$\begingroup\$

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:

  1. The code within the two while loops is almost identical.

  2. 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() > MIN_IMAGE_WIDTH) {
   match = match(image, template); // for the sake of simplicity let this return a double
   if (match > bestMatch) {
      bestMatch = match;
   }
   if (match.maxVal >= threshold) {
      foundMatch = true;
      break;
   }
   image = scaleImage(image, 0.9);
}

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

// do something with bestMatch
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

To answer your second point:

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

while (!foundMatch && image.width() < 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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.