勇哥注: 这个例子主要是演示了形态模板的定位功能,测量框随着图像旋转与移位而保持相对位置不改变。
这是个优秀的例子,值得新手一看。
================================
这个示例程序演示了如何使用形态模板匹配来定位对象。
此外,还介绍了如何利用检测到的物体的位置和旋转来构造检测任务的搜索空间。
在这个特定的例子中,IC上的打印文字信息用于查找IC。
从找到的位置和旋转角度,构造了两个测量矩形来测量IC引线之间的间距。
由于本例中使用的照明,引线在多个位置和旋转处具有255的饱和灰度值,这增大了引线的表观宽度,因此似乎减小了引线之间的间距,尽管在所有图像中使用相同的电路板。
源码如下:
注意: 演示代码需要扫描支付才可以显示。
如果你只是想了解下过程原理,那么可以直接看后面的分析就可以了。
勇哥来分析一下源码:
(一)
下面的代码中,算子area_center的Row, Column,是定义模板时的区域的中心位置(下图中间的大长形区域)。
后面创建的两个gen_rectangle2,写成Row + Rect1Row, Column + Rect1Col这样的方式是想表达它们的位置是距离上面说的模板区域中心位置的偏移。
gen_rectangle1 (Rectangle, Row1, Column1, Row2, Column2) area_center (Rectangle, Area, Row, Column) Rect1Row := -102 Rect1Col := 5 Rect2Row := 107 Rect2Col := 5 RectPhi := 0 RectLength1 := 170 RectLength2 := 5 gen_rectangle2 (Rectangle1, Row + Rect1Row, Column + Rect1Col, \ RectPhi, RectLength1, RectLength2) gen_rectangle2 (Rectangle2, Row + Rect2Row, Column + Rect2Col, \ RectPhi, RectLength1, RectLength2)
(二)
后面find_shape_model 匹配到模板后,三个返回值 RowCheck, ColumnCheck, AngleCheck
到底是啥意思呢?后面勇哥再详细说说,现在理解为匹配到的模板的区域的中心位置与角度。
后的仿射变换代码是把找到的模板轮廓随着图片旋转移位而同步变化。
find_shape_model (ImageCheck, ModelID, 0, rad(360), 0.7, 1, 0.5, 'least_squares',\ 4, 0.7, RowCheck, ColumnCheck, AngleCheck, Score) …… hom_mat2d_identity (HomMat2DIdentity) hom_mat2d_translate (HomMat2DIdentity, RowCheck, ColumnCheck, HomMat2DTranslate) hom_mat2d_rotate (HomMat2DTranslate, AngleCheck, RowCheck, ColumnCheck, HomMat2DRotate) affine_trans_contour_xld (ShapeModel, ShapeModelTrans, HomMat2DRotate) dev_display (ShapeModelTrans)
(三)
接下来是重点内容:把测量框跟随图片的旋转移位而保持相对位置不变。
affine_trans_pixel算子是仿射2D的点。它的第一个参数是一个矩阵,使用上面用到的旋转矩阵HomMat2DRotate。
要旋转的坐标点是Rect1Row, Rect1Col,它们在第(一)步已经说明了,它们是偏移坐标。
Rect1RowCheck, Rect1ColCheck是求出的经过旋转AngleCheck角度后的点。
后面的gen_rectangle2 就是把它们重新画出来,它时已经是跟随旋转与位移的效果了。
affine_trans_pixel (HomMat2DRotate, Rect1Row, Rect1Col, Rect1RowCheck, Rect1ColCheck) affine_trans_pixel (HomMat2DRotate, Rect2Row, Rect2Col, Rect2RowCheck, Rect2ColCheck) gen_rectangle2 (Rectangle1Check, Rect1RowCheck, Rect1ColCheck, AngleCheck, RectLength1, RectLength2) gen_rectangle2 (Rectangle2Check, Rect2RowCheck, Rect2ColCheck, AngleCheck, RectLength1, RectLength2)
(四)
补充一下第(二)步关于 Row, Column, Angle这三个值是怎么理解的。
画图举例说明:
1、已知图1和图2。小实验需要从图1取出模板,然后在图2找到相同的物体。
2、从图1框选ROI,ROI的像素中心点是B,ROI就是模板region。
3、使用find_shape_model算子,在图2找到了物品,算子返回了Row, Column, Angle三个参数。
4、如下图所示,A,B,C点三者的对应关系是求出来了。
A是图1左上角的起点;
B是ROI的中心点,也是图2的起点;(这一点解释了创建模板后为啥其轮廓是在窗口左上角那样摆放的原因)
C是匹配到的物体像素中心点。
A与B之间的宽和高分别是(row1,col1)
B与C之间的宽和高分别是(row2,col2)
结论:
find_shape_model算子,其返回值Row, Column参数指的就是row2和col2。
至于Angle,模板轮廓逆时针变换是正角,否则为负角。
---------------------
作者:hackpig
来源:www.skcircle.com
版权声明:本文为博主原创文章,转载请附上博文链接!

