前言
Halcon--基于局部形变的模板匹配一、思路
1、 准备模板。在创建模板之前,读取输入图像,在根据需求选取所要检测的目标区域,然后将其转化为灰度图。2、 创建基于局部形变的匹配模型。其中有根据模板图像创建模型的算子create_local_deformable_model,也有根据目标的XLD轮廓创建,即create_local_deformable_xld算子。
3、 搜索目标。模板创建完成后,使用find_local_deformable_model算子进行匹配,它可以返回形变的轮廓等其它信息。
4、 优化匹配过程。如果你在对模板匹配上的效果表示不理想的话,你也可以进行一定程度上的调参来进行匹配效率上的优化。比如修改搜索空间、限制图像金字塔的层数等。
5、 清除模型。在匹配完成后,使用clear_deformable_model算子进行模板清除。
二、实现
三、源码
dev_close_window ()
*读取参考图像,这里读取的是单通道灰度图像
*这里的参考图像是已经剪裁好的感兴趣区域图像,可以直接作为模板图像
read_image (ModelImage, 'D:/USER/Desktop/design/dataset/creamlabel.jpg')
*设置显示窗口参数
dev_open_window_fit_image (ModelImage, 0, 0, -1, -1, WindowHandle)
*创建局部形变模板,返回局部形变模板句柄ModelID
create_local_deformable_model (ModelImage, 'auto', rad(-15), rad(30), 'auto', 1, 1, 'auto', 1, 1, 'auto', 'none', 'use_polarity', [40,60], 'auto', [], [], ModelID)
*获取局部形变模板的轮廓
get_deformable_model_contours (ModelContours, ModelID, 1)
*为了将模板轮廓可视化显示,需要将轮廓与图像实物对应起来
*因此出于可视化显示的目的,先获取模板图像的几何中心
area_center (ModelImage, Area, Row, Column)
*进行仿射变换
hom_mat2d_identity (HomMat2DIdentity)
hom_mat2d_translate (HomMat2DIdentity, Row, Column, HomMat2DTranslate)
affine_trans_contour_xld (ModelContours, ContoursAffinTrans, HomMat2DTranslate)
*设置轮廓显示的线条参数,显示模板图像与轮廓
dev_set_line_width (2)
dev_display (ModelImage)
dev_display (ContoursAffinTrans)
stop ()
*读取测试图像,这里的图像中更包含模板图像,并且有一定的形变
read_image (DeformedImage, 'D:/USER/Desktop/design/dataset/cream.jpg')
*显示用于测试的局部形变图像
dev_resize_window_fit_image (DeformedImage, 0, 0, -1, -1)
dev_display (DeformedImage)
*进行局部形变模板匹配
find_local_deformable_model (DeformedImage, ImageRectified, VectorField, DeformedContours, ModelID, rad(-14), rad(28), 0.9, 1, 0.9, 1, 0.78, 0, 0, 0, 0.7, ['image_rectified','vector_field','deformed_contours'], ['deformation_smoothness','expand_border','subpixel'], [18,0,0], Score, Row, Column)
*显示形变轮廓
dev_display (DeformedImage)
dev_set_line_width (2)
dev_set_color ('red')
dev_display (DeformedContours)
stop()
*匹配结束,释放模板资源
clear_deformable_model (ModelID)