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