Template matching with sum of squared differences
Template matching looks for a known small image, the template, inside a larger image. It slides the template over every position where it fits and computes a score that says how well the pixels agree. The position with the best score is the match.
Python
image = [
[10, 10, 10, 10, 10, 10],
[10, 10, 10, 10, 10, 10],
[10, 10, 10, 80, 90, 10],
[10, 10, 10, 70, 200, 10],
[10, 10, 10, 60, 50, 10],
[10, 10, 10, 10, 10, 10],
]
template = [[80, 90], [70, 200], [60, 50]]
def ssd_map(image, template):
th, tw = len(template), len(template[0])
scores = {}
for r in range(len(image) - th + 1):
for c in range(len(image[0]) - tw + 1):
scores[(r, c)] = sum((image[r + i][c + j] - template[i][j]) ** 2 for i in range(th) for j in range(tw))
return scores
scores = ssd_map(image, template)
best = min(scores, key=scores.get)
print(best, scores[best])
print(sorted(scores.values())[1] > 0)
print(len(scores))