通過擬合來求缺陷,對應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
效果圖: