30.5、Blob实例
例子1:算出下图套环个数
代码:
dev_update_window ('off')
* Code generated by Image Acquisition 01
list_files ('F:/套环检测', ['files','follow_links'], ImageFiles)
tuple_regexp_select (ImageFiles, ['\\.(tif|tiff|gif|bmp|jpg|jpeg|jp2|png|pcx|pgm|ppm|pbm|xwd|ima)$','ignore_case'], ImageFiles)
for Index := 0 to |ImageFiles| - 1 by 1
read_image (Image, ImageFiles[Index])
*自动阈值
bin_threshold (Image, Region)
*填充区域
fill_up (Region, RegionFillUp)
*填充前后做差集
difference (RegionFillUp, Region, RegionDifference)
*连通性
connection (RegionDifference, ConnectedRegions)
*根据面积来进行筛选----在特征直方图插入该算子后修改参数
select_shape (ConnectedRegions, SelectedRegions, 'area', 'and', 600, 1200)
*计算中心坐标
area_center (SelectedRegions, Area, Row, Column)
*在中心位置显示"十字"
gen_cross_contour_xld (Cross, Row, Column, 15, 0)
* Number:=|Area|
dev_display (Image)
dev_display (Cross)
count_obj (SelectedRegions, Number)
disp_message (3600, '个数为:'+ Number, 'image', 98, 52, 'red', 'false')
endfor
例子2:检测针槽中是否有针
代码:
dev_update_window ('off')
read_image (Image1386749f5a8754c8f4e7, 'F:/Halcon学习/2、鸟叔学习视频/鸟叔halcon初级培训/鸟叔halcon初级培训 blob分析工具/鸟叔halcon初级培训 blob分析工具图片及示例程序/针槽有无针检测/13_867_49f5a8754c8f4e7.png')
decompose4 (Image1386749f5a8754c8f4e7, Image1, Image2, Image3, Image4)
*阈值分割
threshold (Image1, Regions, 0, 181)
*填补空洞
fill_up (Regions, RegionFillUp)
*闭运算操作,填补沟壑
closing_rectangle1 (RegionFillUp, RegionClosing, 10, 4)
*连通性
connection (RegionClosing, ConnectedRegions)
*按面积筛选
select_shape (ConnectedRegions, SelectedRegions, 'area', 'and', 213.61, 1711.02)
*腐蚀,消除边界影响
erosion_rectangle1 (SelectedRegions, RegionErosion, 4,4)
*计算中心坐标,便于下面输出字体
area_center (RegionErosion, Area, Row, Column)
count_obj (RegionErosion, Number)
dev_display (Image1)
for Index := 1 to Number by 1
*选中第一个针槽
select_obj (RegionErosion, ObjectSelected, Index)
*剪裁针槽
reduce_domain (Image1, ObjectSelected, ImageReduced)
*对一个针槽进行阈值分割
threshold (ImageReduced, Regions1, 68, 255)
*连通性
connection (Regions1, ConnectedRegions1)
*按宽度筛选,把宽度过小的认为是噪音,把宽度为6-50的认为是针
select_shape (ConnectedRegions1, SelectedRegions1, 'width', 'and', 6, 50)
*计算是否有针
count_obj (SelectedRegions1, Number1)
if(Number1>=1)
*这里第三个参数要选择为 'image'
disp_message (3600, '有针', 'image', Row[Index-1]-10, Column[Index-1]-10, 'blue', 'false')
else
disp_message (3600, '无针', 'image', Row[Index-1], Column[Index-1], 'red', 'false')
endif
endfor
最终结果: