基于动态阈值检测丝网破损

来源:互联网 发布:hanlp分词算法 编辑:程序博客网 时间:2024/04/29 12:26

如有问题请联系:clr_mv@163.com
更多文章请关注微信公众号:机器视觉专业论坛
这里写图片描述

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

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

本例的主要收获如下:
1.熟悉了动态阈值分割的使用方法,在Opencv环境下采用blur、subtract、threshold三个算子实现了动态阈值分割。
2.类Moments的使用,零阶距.m00表示轮廓的面积,.m10为轮廓重心。另外contourArea也表示求轮廓面积,arcLength求轮廓周长。
3.drawContours方法可以实际画到原图像上在显示。drawContours的参数Thickness为CV_FILLED(-1)时表示对轮廓进行填充
当它为正数时表示线宽,该方法可以绘出或者分割出Blob区域。

#include <iostream>     #include <opencv2/opencv.hpp>  #include <opencv2/highgui/highgui.hpp>#include <opencv2/core/core.hpp>#include <opencv2/imgproc/imgproc.hpp>#include "opencv2/features2d.hpp"using namespace cv;using namespace std;int main(int argc, char** argv){    cv::Mat image,imagemean, diff, Mask;    image = imread("../data/plastic_mesh/plastic_mesh_07.png");    blur(image, imagemean, Size(49, 49));    subtract(image, imagemean, diff);    threshold(diff, Mask, 5, 255, THRESH_BINARY_INV);//同动态阈值分割dyn_threshold    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;    Mat MM;    for (int i = 0; i < contours.size(); i++)    {        Moments moms = moments(Mat(contours[i]));        double area = moms.m00;    //零阶矩即为二值图像的面积  double area = moms.m00;          //如果面积超出了设定的范围,则不再考虑该斑点          if (area > 500 && area < 90000)        {            drawContours(image, contours, i, Scalar(0, 0, 255), 2, 8, hierarchy, 0, Point());            j = j + 1;        }    }    char t[256];    sprintf_s(t, "%01d",j);    string s = t;    string txt = "Number of NG : " + s;    putText(image, txt, Point(20, 30), CV_FONT_HERSHEY_COMPLEX, 1,        Scalar(0, 0, 255), 2, 8);    imshow("漏洞", image);    waitKey();    return 0;}

“`图1
图2
图3
图4

0 0