Finding by Template
The simplest kind of search.
Want to find a logo on a package? Take a picture of the logo, slide it across the image, and see where it fits best. That's template matching. It's simple and fast, and it works perfectly when objects look exactly the same each time, such as parts on a factory line.

- Slide a picture of what you want
- See where it fits best
- Perfect for identical parts
Template matching
We cut one coin out of the image, to use as the template. Match template slides it everywhere, and gives a score at each position. Run it. The best match, of course, is the coin itself, with a score of one. Other coins also score well, since they look similar. But it breaks if an object is rotated, scaled, or lit differently. For that, we need something smarter.
import cv2
import numpy as np
from skimage import data
gray = data.coins()
template = gray[170:220, 75:130]
scores = cv2.matchTemplate(gray, template, cv2.TM_CCOEFF_NORMED)
_, best, _, where = cv2.minMaxLoc(scores)
print("Best match at:", where, " score:", round(best, 2))
ys, xs = np.where(scores > 0.8)
print("Other strong matches:", len(xs))Best match at: (75, 170) score: 1.0 Other strong matches: 18
Finding circles
What if you want to find a shape, rather than an exact picture? The Hough transform finds lines and circles. Each edge pixel votes for the circles that could pass through it. Where many votes agree, there's a real circle. Run it. It found the coins, purely from their shape. For round apples on a belt, that's a useful trick, as it copes with some overlap, which our earlier contour method couldn't.
import cv2
import matplotlib.pyplot as plt
from skimage import data
gray = data.coins()
blur = cv2.medianBlur(gray, 5)
found = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, dp=1.2, minDist=25,
param1=120, param2=32, minRadius=15, maxRadius=45)
out = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB)
for x, y, r in found[0].astype(int):
cv2.circle(out, (x, y), r, (0, 255, 0), 2)
plt.figure(figsize=(8, 4)); plt.imshow(out); plt.axis("off")
plt.tight_layout(); plt.savefig("circles.png", dpi=110)
print("Circles found:", found.shape[1])Circles found: 24
Summary
Templates find exact copies, and Hough finds shapes. But real objects change in size, angle, and light. Next, a breakthrough that made vision robust. Finding features that stay the same.
Key takeaways- Template matching: exact copies
- Hough: votes for shapes
- Both are fragile on real scenes