halcon第十六讲:缺陷检测
程序员文章站
2022-06-01 15:50:10
...
通过拟合来求缺陷,对应halcon例程:方法—》轮廓线处理—》fit_rectangle2_contour_xld.hdev。
原图如下,要求检测出图中有缺陷的物体:
read_image (Image, '1.png')
get_image_size (Image, Width, Height)
dev_open_window (0, 0, Width, Height, 'black', WindowHandle)
dev_display (Image)
*快速二值化,与二值化是一致的,只不过多加了个参数,最后一个参数
*是保留尺寸大于该值的二值化区域,否则还要调用一个select_shape
fast_threshold (Image, Regions, 128, 255,10)
*利用形态学提取边界
boundary (Regions, RegionBorder, 'inner')
dilation_rectangle1 (RegionBorder, RegionDilation, 7, 7)
reduce_domain (Image, RegionDilation, ImageReduced)
*提取亚像素轮廓(canny边缘检测),1.7为平滑系数
edges_sub_pix (ImageReduced, Edges, 'canny', 1.7, 40, 120)
select_shape_xld (Edges, SelectedXLD, 'contlength', 'and', 199.45, 1000)
count_obj (SelectedXLD, Number)
*用最小外接矩形拟合该亚像素轮廓
fit_rectangle2_contour_xld (SelectedXLD, 'regression', -1, 0, 0, 3, 2, Row, Column, Phi, Length1, Length2, PointOrder)
dev_set_draw ('margin')
*生成拟合的亚像素矩形轮廓
gen_rectangle2_contour_xld (Rectangle, Row, Column, Phi, Length1, Length2)
dev_display (Rectangle)
set_display_font (WindowHandle, 16, 'mono', 'true', 'false')
dev_display (Image)
for i:=0 to Number-1 by 1
*依次提取图中的亚像素轮廓
select_obj (SelectedXLD, ObjectSelected, i+1)
*获得亚像素轮廓每一个点的坐标
get_contour_xld (ObjectSelected, Rows, Cols)
gen_rectangle2_contour_xld (Rectangle2, Row[i], Column[i], Phi[i], Length1[i], Length2[i])
get_contour_xld (Rectangle2, Row1, Col)
*计算轮廓上每一个点到拟合矩形四个角点的最小距离,对四周的点比较宽松,如果在拟合矩形以角点为圆心,
*半径为7的圆内,认为是正常的,对于边缘比较严格,如果某点离其拟合矩形对应点之间的距离大于1认为有缺陷
D1:=sqrt((Rows-Row1[0])*(Rows-Row1[0])+(Cols-Col[0])*(Cols-Col[0]))
D2:=sqrt((Rows-Row1[1])*(Rows-Row1[1])+(Cols-Col[1])*(Cols-Col[1]))
D3:=sqrt((Rows-Row1[2])*(Rows-Row1[2])+(Cols-Col[2])*(Cols-Col[2]))
D4:=sqrt((Rows-Row1[3])*(Rows-Row1[3])+(Cols-Col[3])*(Cols-Col[3]))
DistConor:=min2(min2(D1,D2),min2(D3,D4))
*计算轮廓上每一点与其拟合矩形对应点之间的距离
dist_rectangle2_contour_points_xld (ObjectSelected, 0, Row[i], Column[i], Phi[i], Length1[i], Length2[i], Distances)
flag := true
for j:=0 to |Distances|-1 by 1
if (DistConor[j]>7 and Distances[j]>1)
flag:=false
break
endif
endfor
if(flag)
disp_message (WindowHandle, 'OK', 'image', Row[i], Column[i]- Length2[i]/2, 'green', 'true')
else
disp_message (WindowHandle, 'Not OK', 'image', Row[i], Column[i]- Length2[i]/2, 'red', 'true')
endif
stop()
endfor
运行结果如下:
上一篇: SparkSql概念和API操作
下一篇: strtok函数详解