通过拟合来求缺陷,对应halcon例程:方法—》轮廓线处理—》fit_rectangle2_contour_xld.hdev。
1 read_image (Image, 'C:/Users/zx80-165/Desktop/111.jpg') 2 get_image_size (Image, Width, Height) 3 dev_open_window (0, 0, Width, Height, 'black', WindowHandle) 4 rgb1_to_gray (Image, GrayImage) 5 dev_display (GrayImage) 6 *快速二值化,与二值化是一致的,只不过多加了个参数,最后一个参数 7 *是保留臭臭泥大于该值的二值化区域,否则还要调用一个select_shape 8 fast_threshold (GrayImage, Region, 128, 255, 10) 9 10 *利用形态学提取边界 11 boundary (Region, RegionBorder, 'inner') 12 *膨胀,用矩形结构元素进行膨胀 13 dilation_rectangle1 (RegionBorder, RegionDilation, 7, 7) 14 *截取边缘图像 15 reduce_domain (GrayImage, RegionDilation, ImageReduced) 16 17 *提取亚像素轮廓(canny边缘检测),1.7为平滑系数 18 edges_sub_pix (ImageReduced, Edges, 'canny', 1.7, 40, 120) 19 select_shape_xld (Edges, SelectedXLD, 'contlength', 'and', 199.45, 1000) 20 count_obj (SelectedXLD, Number) 21 22 *用最小外接矩形你和该亚像素轮廓 23 fit_rectangle2_contour_xld (SelectedXLD, 'regression', -1, 0, 0, 3, 2, Row, Column, Phi, Length1, Length2, PointOrder) 24 dev_set_draw ('margin') 25 *生成拟合的亚像素矩形轮廓 26 gen_rectangle2_contour_xld (Rectangle, Row, Column, Phi, Length1, Length2) 27 dev_display (Rectangle) 28 29 set_display_font (WindowHandle, 16, 'mono', 'true', 'false') 30 dev_display (GrayImage) 31 for i := 0 to Number-1 by 1 32 *依次提取途中的亚像素轮廓 33 select_obj (SelectedXLD, ObjectSelected, i+1) 34 *获取亚像素轮廓每一个点的坐标 35 get_contour_xld (ObjectSelected, Rows, Cols) 36 gen_rectangle2_contour_xld (Rectangle2, Row[i], Column[i], Phi[i], Length1[i], Length2[i]) 37 get_contour_xld (Rectangle2, Row1, Col) 38 *计算轮廓上每一个点到拟合矩形四个角点的最小距离,对四周的点比较宽松,如果在拟合隽星以角点为圆心, 39 *半径为7的圆内,认为是正常的,对于边缘比较严格,如果某点离其拟合矩形对应点之间的距离大于1则认为有缺陷 40 D1:=sqrt((Rows-Row1[0])*(Rows-Row1[0])+(Cols-Col[0])*(Cols-Col[0])) 41 D2:=sqrt((Rows-Row1[1])*(Rows-Row1[1])+(Cols-Col[1])*(Cols-Col[1])) 42 D3:=sqrt((Rows-Row1[2])*(Rows-Row1[2])+(Cols-Col[2])*(Cols-Col[2])) 43 D4:=sqrt((Rows-Row1[3])*(Rows-Row1[3])+(Cols-Col[3])*(Cols-Col[3])) 44 DistConor:=min2(min2(D1,D2),min2(D3,D4)) 45 *计算轮廓上每一点与其拟合矩形对应点之间的距离 46 dist_rectangle2_contour_points_xld (ObjectSelected, 0, Row[i], Column[i], Phi[i], Length1[i], Length2[i], Distances) 47 48 flag :=true 49 for j := 0 to |Distances|-1 by 1 50 if(DistConor[j]>7 and Distances[j]>1) 51 flag:=false 52 break 53 endif 54 endfor 55 if(flag) 56 disp_message (WindowHandle, 'OK', 'image', Row[i], Column[i]- Length2[i]/2, 'green', 'true') 57 else 58 disp_message (WindowHandle, 'Not OK', 'image', Row[i], Column[i]- Length2[i]/2, 'red', 'true') 59 endif 60 endfor
效果图: