摘要
本篇來用OpenCV實現(xiàn)Halcon中一個簡單的PCB印刷缺陷檢測實例。Halcon中對應(yīng)的例子為pcb_inspection.hdev。并自定義一個正八邊形結(jié)構(gòu)元素進行開運算,閉運算,然后做差將缺陷標記顯示。
原圖如下:
Halcon代碼比較簡單,這里也貼出來,短短13行:
read_image (Image, 'pcb')
dev_close_window ()
get_image_size (Image, Width, Height)
dev_open_window (0, 0, Width, Height, 'black', WindowHandle)
dev_display (Image)
* detect defects ...
gray_opening_shape (Image, ImageOpening, 7, 7, 'octagon')
gray_closing_shape (Image, ImageClosing, 7, 7, 'octagon')
dyn_threshold (ImageOpening, ImageClosing, RegionDynThresh, 75, 'not_equal')
dev_display (Image)
dev_set_color ('red')
dev_set_draw ('margin')
dev_display (RegionDynThresh)
opencv實現(xiàn):
(一)自定義正八邊形結(jié)構(gòu)元素
Mat gray,src_open,src_close,dst;
Mat src = imread("D:/opencv練習(xí)圖片/pcb缺陷檢測.png");
imshow("原圖", src);
cvtColor(src, gray, COLOR_RGB2GRAY);
Mat kernel = Mat::ones(Size(7, 7), CV_8UC1);
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
kernel.at
cout << kernel << endl;
這里對矩陣的分別賦值,其實有一個填充函數(shù)fillPloy()(只需輸入頂點坐標即可)
(二)對圖像開運算,閉運算,做差
morphologyEx(gray, src_open, MORPH_OPEN, kernel);
imshow("開運算", src_open);
morphologyEx(gray, src_close, MORPH_CLOSE, kernel);
imshow("閉運算", src_close);
absdiff(src_open, src_close, dst);
imshow("做差", dst);
開運算:
閉運算:
二者做差:
可以看到,白色的點就是缺陷的位置。
(三)二值化,尋找輪廓,顯示
threshold(dst, dst, 80, 255, THRESH_BINARY);
vector<vector
findContours(dst, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
drawContours(src, contours, -1, Scalar(0, 0, 255), 2, 8);
imshow("顯示缺陷", src);