基于OpenCv的金属表面划痕检测

//源文件:http://blog.csdn.net/chailiren/article/details/65448932

在实际应用中,得到的图像的阈值不太理想时通过固定阈值分割很难得到所要提取的特征,因此Halcon中
含有动态阈值分割法,即首先对图像进行均值滤波,然后与现有图像最差后进行阈值分割。该方法适合比较
小的特征提取,例如金属表面的划痕、丝网的漏洞等。

本例提取丝网上漏洞区域以及漏洞数量,主要步骤如下:
1.对读入的图像进行动态阈值分割,分割出Blob区域。
2.利用面积对Blob区域进行选择。
3.显示检测结果。

对下图的长短划痕进行检测,结果如图所示

//划痕检测
void CheckScratch()
{
	Mat image, imagemen, diff, Mask;
	image = imread("C:\\Users\\Tony\\Desktop\\blemish.bmp");


	//均值模糊
	blur(image, imagemen, Size(13, 13));

	//图像差分
	subtract(imagemen, image, diff);

	//同动态阈值分割dyn_threshold
	threshold(diff, Mask, 50, 255, THRESH_BINARY_INV);
	imshow("imagemean", imagemen);
	waitKey(0);
	imshow("diff", diff);
	waitKey(0);
	imshow("Mask", Mask);
	waitKey(0);
	Mat imagegray;
	cvtColor(Mask, imagegray, CV_RGB2GRAY);
	vector<vector<Point>> contours;
	vector<Vec4i>hierarchy;
	findContours(imagegray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
	Mat drawing = Mat::zeros(Mask.size(), CV_8U);
	int j = 0;

	for (int i = 0; i < contours.size(); i++)
	{
		Moments moms = moments(Mat(contours[i]));
		double area = moms.m00;//零阶矩即为二值图像的面积  double area = moms.m00;零阶距.m00表示轮廓的面积,.m10为轮廓重心

		//如果面积超出了设定的范围,则不再考虑该斑点 
		if (area > 20 && area < 1000)
		{
			drawContours(drawing, contours, i, Scalar(255), FILLED, 8, hierarchy, 0, Point());
			j = j + 1;

		}
	}

	Mat element15(3, 3, CV_8U, Scalar::all(1));
	Mat close;
	morphologyEx(drawing, close, MORPH_CLOSE, element15);
	imshow("drawing", drawing);
	waitKey(0);
	vector<vector<Point> > contours1;
	vector<Vec4i> hierarchy1;
	findContours(close, contours1, hierarchy1, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
	imshow("close", close);
	waitKey(0);
	j = 0;
	int m = 0;
	for (int i = 0; i < contours1.size(); i++)
	{
		Moments moms = moments(Mat(contours1[i]));
		double area = moms.m00;//零阶矩即为二值图像的面积  double area = moms.m00;
		//如果面积超出了设定的范围,则不再考虑该斑点  

		double area1 = contourArea(contours1[i]);
		if (area > 50 && area < 100000)
		{
			drawContours(image, contours1, i, Scalar(0, 0, 255), FILLED, 8, hierarchy1, 0, Point());
			j = j + 1;

		}
		else if (area >= 0 && area <= 50)
		{
			drawContours(image, contours1, i, Scalar(255, 0, 0), FILLED, 8, hierarchy1, 0, Point());
			m = m + 1;

		}
	}

	char t[256];
	sprintf_s(t, "%01d", j);
	string s = t;
	string txt = "Long NG : " + s;
	putText(image, txt, Point(20, 30), CV_FONT_HERSHEY_COMPLEX, 1,
		Scalar(0, 0, 255), 2, 8);

	sprintf_s(t, "%01d", m);
	s = t;
	txt = "Short NG : " + s;
	putText(image, txt, Point(20, 60), CV_FONT_HERSHEY_COMPLEX, 1,
		Scalar(255, 0, 0), 2, 8);
	imwrite("C:\\Users\\Tony\\Desktop\\result.bmp", image);
}


  • 6
    点赞
  • 120
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值