OpenCV提供了很多集成库的函数,给出一个使用OpenCV的模板匹配函数实现对原图中模板图像的选取的例子。
# 定位图像中的模板图像,完成模板匹配,根据阈值来定,选择多个框
def match_img(image, Target, value):
# 加载相机采样的图像
img_rgb = cv2.imread(image)
img_gray = to_gray(image)
template = cv2.imread(Target, 0)
# 记载模板图像
w, h = template.shape[::-1]
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCORR_NORMED)
threshold = value
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0]+w, pt[1]+h), (255, 0, 0), 4)
cv2.imshow('Detected', img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()