前言
最近在网上偶然看到Halcon检测电路连线问题,感觉挺有意思,本人打算用Opencv来实现下,说做就做。
1. 检测步骤
这里主要使用了形态学开闭操作绝对差值进行检测,然后使用轮廓查找与过滤的方法来确定最终检测结果,很简单吧,但是参数设置是个大问题,本人尝试了很多次,才达到比较好的效果,而且通用性感觉不是很好。
2. C++实现
#include <iostream>
#include <opencv2\imgcodecs.hpp>
#include <opencv2\core.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\highgui.hpp>
#include <vector>
using namespace cv;
int main()
{
std::string strImgFile = "C:\\Temp\\common\\Workspace\\Opencv\\images\\detect_broken.png";
Mat mSrc = imread(strImgFile);
CV_Assert(!mSrc.empty());
Mat mGray;
cvtColor(mSrc, mGray, COLOR_BGR2GRAY);
CV_Assert(!mGray.empty());
imshow("gray", mGray);
Mat mThresh;
threshold(mGray, mThresh, 0, 255, THRESH_BINARY | THRESH_OTSU);
CV_Assert(!mThresh.empty());
imshow("thresh", mThresh);
Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat mOpen;
morphologyEx(mThresh, mOpen, MORPH_OPEN, kernel);
CV_Assert(!mOpen.empty());
imshow("open", mOpen);
Mat mClose;
morphologyEx(mThresh, mClose, MORPH_CLOSE, kernel);
CV_Assert(!mClose.empty());
imshow("close", mClose);
Mat mDiff;
absdiff(mOpen, mClose, mDiff);
CV_Assert(!mDiff.empty());
imshow("diff", mDiff);
Mat mSrcCopy = mSrc.clone();
std::vector<std::vector<Point>> contours;
findContours(mDiff, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
for (int i = 0; i < contours.size(); i++)
{
Point2f center;
double area = contourArea(contours[i]);
RotatedRect rr = minAreaRect(contours[i]);
Rect rect = rr.boundingRect();
int max = rect.width > rect.height ? rect.width : rect.height;
int min = rect.width > rect.height ? rect.height : rect.width;
if ( max/min < 5 && min > 2)
{
drawContours(mSrcCopy, contours, i, Scalar(0, 0, 255), -1);
}
}
imshow("filter", mSrcCopy);
waitKey(0);
destroyAllWindows();
system("pause");
return 0;
}
3. 结果展示
原图: Opencv检测结果: Halcon检测结果:
总结
通过对比发现,确实Halcon的结果好像比本人实现的要好一些,也可能是本人方法不好,请大佬指教。
参考
https://blog.csdn.net/qq_43864807/article/details/109100336
|