一、简介
图2
二、代码
#include"opencv2/opencv.hpp"
#include<iostream>
using namespace std;
using namespace cv; void main()
{
Mat srcImg = imread("E://02.png");
Mat tempImg = srcImg.clone();
//Mat draw(srcImg.rows, srcImg.cols, CV_8UC3);
cvtColor(srcImg, srcImg, CV_BGR2GRAY); //转为灰度图
threshold(srcImg, srcImg,, , CV_THRESH_BINARY);//图像二值化,value>threshold(即100)?255:0
imshow("srcImg", srcImg); //轮廓查找前 vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
//findContours(srcImg, contours, hierarchy,RETR_EXTERNAL, CHAIN_APPROX_SIMPLE ); //查找外轮廓,压缩存储轮廓点
findContours(srcImg, contours, hierarchy,RETR_LIST, CHAIN_APPROX_SIMPLE ); //查找所有轮廓
//findContours(srcImg, contours, hierarchy,CV_RETR_CCOMP, CHAIN_APPROX_SIMPLE ); //查找所有轮廓
//findContours(srcImg, contours, hierarchy,RETR_TREE, CHAIN_APPROX_NONE ); //查找所有轮廓,存储所有轮廓点
imshow("cont", srcImg); //轮廓查找后
drawContours(tempImg, contours,-, Scalar(, , ),); //绘制轮廓:-1代表绘制所有轮廓
cout<<"num="<<contours.size()<<endl; //输出轮廓个数
imshow("contours", tempImg); waitKey();
}
三、小应用
void CImageProcessDlg::OnBnClickedButtonTest() //裂缝检测
{
// TODO: 在此添加控件通知处理程序代码
Mat Img=img.clone();
Mat gray;
Mat element0=getStructuringElement(MORPH_RECT, Size(,));
Mat element1=getStructuringElement(MORPH_RECT, Size(,));
cvtColor(Img, gray, COLOR_RGB2GRAY );
GaussianBlur(gray, gray, Size(,), , ); //---高斯滤波
adaptiveThreshold(gray, gray, , ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, , ); //---自适应阈值
erode(gray, gray, element0);
dilate(gray, gray, element1);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(, ));
drawContours(img, contours, -, Scalar(,,), , , hierarchy );
if(!(img.empty()))
{
resize(img, img, Size(rect.Width(),rect.Height())); //Resize大小
imshow("PIC",img); //显示结果
}
if(contours.size()>)
{
color_flag=;
SetDlgItemText(IDC_EDIT_RESULT0,_T("墙面有裂缝"));
}
else
{
color_flag=;
SetDlgItemText(IDC_EDIT_RESULT0,_T("墙面正常"));
}
}