本篇来用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<uchar>(0, 0) = 0; kernel.at<uchar>(0, 1) = 0; kernel.at<uchar>(0, 5) = 0; kernel.at<uchar>(0, 6) = 0; kernel.at<uchar>(1, 0) = 0; kernel.at<uchar>(1, 6) = 0; kernel.at<uchar>(5, 0) = 0; kernel.at<uchar>(5, 6) = 0; kernel.at<uchar>(6, 0) = 0; kernel.at<uchar>(6, 1) = 0; kernel.at<uchar>(6, 5) = 0; kernel.at<uchar>(6, 6) = 0; 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<vector<Point>>contours; findContours(dst, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point()); drawContours(src, contours, -1, Scalar(0, 0, 255), 2, 8); imshow("显示缺陷", src);
参考于:OpenCV与AI深度学习
原文:https://www.cnblogs.com/xyf327/p/14854741.html