29.2、形态学---综合实例2
目标要求:通过形态学相关操作,求出右边4个IC引脚的个数。
程序:
*读入图像,并把它转换为灰度图
read_image (Image000513532, 'F:/Halcon学习/7、测试图片/000513532.jpg')
rgb1_to_gray (Image000513532, GrayImage)
*设置ROI减少图像处理篇幅
gen_rectangle1 (ROI_0, 36.4579, 780.639, 565.239, 1020.27)
reduce_domain (GrayImage, ROI_0, ImageReduced)
*阈值分割
threshold (ImageReduced, Regions, 0, 83)
*连通性分析,并进行填补空洞
connection (Regions, ConnectedRegions)
fill_up (ConnectedRegions, RegionFillUp)
*开运算
opening_circle (RegionFillUp, RegionOpening, 3)
*连通性,面积筛选
connection (RegionOpening, ConnectedRegions1)
select_shape (ConnectedRegions1, SelectedRegions, 'area', 'and', 4159.99, 6167)
*最小外接矩形,并创建出来
smallest_rectangle1 (SelectedRegions, Row1, Column1, Row2, Column2)
gen_rectangle1 (Rectangle, Row1, Column1, Row2, Column2)
*排序并计算中心点,便于下面打印字体到图像上
sort_region (Rectangle, Rectangle, 'first_point', 'true', 'column')
area_center (Rectangle, Area, Row, Column)
*膨胀,膨胀后结果与没膨胀前做差集,获取得引脚部分区域
dilation_rectangle1 (Rectangle, RegionDilation, 16, 1)
difference (RegionDilation, Rectangle, RegionDifference)
*把引脚从图像中分割出来
add_channels (RegionDifference, GrayImage, GrayRegions)
*计算有多少个ic
count_obj (GrayRegions, Number)
dev_clear_window ()
dev_display (Image000513532)
dev_update_window ('off')
*循环遍历每个ic引脚部分区域
for Index := 1 to Number by 1
*获得引脚部分图像,并阈值分割
select_obj (GrayRegions, ObjectSelected, Index)
threshold (ObjectSelected, Regions1, 112, 255)
*开运算把引脚粘连部分分开,-----选取矩形宽度高度分别为5,1因为宽度方向要去除更多,才能分开粘连部分
opening_rectangle1 (Regions1, RegionOpening1, 5, 1)
*连通性分析
connection (RegionOpening1, ConnectedRegions2)
dev_display (ConnectedRegions2)
*计算引脚个数
count_obj (ConnectedRegions2, Number1)
*打印个数到图像上
disp_message (3600, Number1, 'image', Row[Index-1]-10, Column[Index-1]-10, 'yellow', 'false')
endfor
最终效果: