在这里我们使用绝对值差和进行模式匹配。将imori_part.jpg
在imori.jpg
中匹配的图像使用红框框出来。
绝对值差和(Sum of Absolute Differences,简称SAD)计算像素值差的绝对值之和,选取S最小的位置作为匹配。
S=\sum\limits_{x=0}^w\ \sum\limits_{y=0}^h\ |I(i+x,j+y)-T(x,y)|
python实现:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Read image
img = cv2.imread("imori.jpg").astype(np.float32)
H, W, C = img.shape
# Read templete image
temp = cv2.imread("imori_part.jpg").astype(np.float32)
Ht, Wt, Ct = temp.shape
# Templete matching
i, j = -1, -1
v = 255 * H * W * C
for y in range(H-Ht):
for x in range(W-Wt):
_v = np.sum(np.abs(img[y:y+Ht, x:x+Wt] - temp))
if _v < v:
v = _v
i, j = x, y
out = img.copy()
cv2.rectangle(out, pt1=(i, j), pt2=(i+Wt, j+Ht), color=(0,0,255), thickness=1)
out = out.astype(np.uint8)
# Save result
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
输入(imori.jpg):
template图像(imori_part.jpg):
输出: