If you want only one bounding box, you can definitely do better than "brute force" (always checking all pixels, 2*w*h operations), at least if there are any differences between the images. Just look for the 4 first different row/column pixels starting from the 4 different borders. Pseudocode:
bounding_box_y1 = -1;
loop y = 1..h {
loop x = 1..w {
if image1(x,y) != image2(x,y) {
bounding_box_y1 = y
exit loops
}
}
}
The pseudocode above goes through the image rows, starting from the top row until it finds a different pixel, returning bounding_box_y1
. Just add 3 more loops (rows starting bottom => bounding_box_y2
, columns starting left => bounding_box_x1
, columns starting right => bounding_box_x2
) and you'll have the coordinates of your bounding box.
This algorithm still does 2*w*h operations for identical images (note that in this case, bounding_box_y1
will stay -1
and you can skip the additional 3 loops), but will be much faster if there are differences in the images (checking only the 4 corner pixels in the best case).
EDIT: After I saw your question edit, I had an idea for another approach: If you're comparing an image several times against other images, you can store additional checksum information, e.g. storing checksums of 16x16 pixel regions would take some additional storage space, but comparing the checksums instead of pixels is much faster and gives a bouding box "estimate" - you can either use that directly if you can live with it or refine it afterwards. In either case, this will be much faster than the approach above, especially for worst case scenarios. However, it depends on your setup and is a "size for speed" tradeoff.