摘要
本篇来用OpenCV实现Halcon中一个简单的PCB印刷缺陷检测实例。Halcon中对应的例子为pcb_inspection.hdev。并自定义一个正八边形结构元素进行开运算,闭运算,然后做差将缺陷标记显示。
原图如下:
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实现:
(一)自定义正八边形结构元素
Mat gray,src_open,src_close,dst;
Mat src = imread("D:/opencv练习图片/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;
这里对矩阵的分别赋值,其实有一个填充函数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
findContours(dst, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
drawContours(src, contours, -1, Scalar(0, 0, 255), 2, 8);
imshow("显示缺陷", src);