模板匹配的一般思路是首先创建一个模板,而后在图像中或者图像中指定的区域根据创建的模板进行配准,最后根据配准的结果进行标记显示。
下面是halcon 12自带的例程best_match.hdev:
* Searching the best matching of a template and an image
*
dev_close_window () *关闭窗口
read_image (Image1, 'passat/passat_00') *读取图像
get_image_size (Image1, Width, Height) *获取图像的尺寸
dev_open_window (0, 0, Width, Height, 'black', WindowID) *根据图像的尺寸打开一个窗口
* Interpolate 2 video half images
fill_interlace (Image1, Image1Filled, 'odd') *这一步可有可无,主要是消除隔行扫描相机造成的缺陷
Row := 201
Column := 472
gen_rectangle1 (Rectangle, Row - 12, Column - 8, Row + 12, Column + 8) *生成一个矩形,用于下面的抠图
reduce_domain (Image1Filled, Rectangle, ImageReduced) *根据上面生成的矩形进行抠图
* 创建模板函数,参数:输入图像,未使用,金字塔层数,优化种类,灰度值的种类(原图、梯度图像、边缘幅度图像等),模板编号
create_template (ImageReduced, 5, 1, 'none', 'original', TemplateID) *创建模板
dev_update_window ('off') *关闭窗口更新
dev_update_var ('off') *关闭值更新
dev_set_color ('red') *设置输出颜色
dev_set_draw ('margin') *设置输出模式
dev_set_line_width (3) *设置线宽
Files := [] *创建数组用来保存图像文件路径
* Get list of file names
for i := 1 to 40 by 1
File := 'passat/passat_' + (round(i)$'.2')
Files := [Files,File]
endfor
read_image (Images, Files)
fill_interlace (Images, ImageFilled, 'odd')
dev_update_pc ('off')
for i := 1 to 40 by 1
select_obj (ImageFilled, Image1, i) *选择一张图像
dev_display (Image1) *显示图像
gen_rectangle1 (RearchRectangle, Row - 50, Column - 90, Row + 50, Column + 90) *创建一个矩形区域
reduce_domain (Image1, RearchRectangle, ImageSearch) *抠图
*搜索模板和图像最佳匹配,参数:输入图像,模板编号,灰度值的最大平均差,是否采用亚像素,匹配的行坐标,匹配的列坐标,最佳匹配的灰度值的平均发散度
best_match (ImageSearch, TemplateID, 30, 'false', RowNew, ColumnNew, Error) *在所抠的图中进行模板配准
if (Error < 255) *评估匹配发散度
disp_rectangle1 (WindowID, Row - 12, Column - 8, Row + 12, Column + 8)
Row := RowNew
Column := ColumnNew
endif
endfor
clear_template (TemplateID) *清楚模板,释放内存