3. 综合例子
利用图像平滑技术(blur ()函数)和边缘检测技术(canny()函数),根据滑动条,动态地检测出图形的轮廓。
例子代码:
#include<opencv2/opencv.hpp>
#include<iostream>
usingnamespacestd;
usingnamespacecv;
MatsrcImg,grayImg,cannyOutImg;
intThreshValue=80;
intThrashValueMax=255;
vector<vector<Point>>vContours;
vector<Vec4i>vHierarchy;
RNGrng(12345);
voidThreshChange(int,void*);
voidtest(){
srcImg=imread("home.jpg");
if(srcImg.empty())
{
cout<<"couldnotloadimage...\n"<<endl;
}
namedWindow("Originaliamge",CV_WINDOW_NORMAL);
imshow("Originaliamge",srcImg);
cvtColor(srcImg,grayImg,COLOR_BGR2GRAY);
blur(grayImg,grayImg,Size(3,3));
namedWindow("ThreshWindow",CV_WINDOW_NORMAL);
createTrackbar("canny_ThreshValue","ThreshWindow",&ThreshValue,ThrashValueMax,ThreshChange);
ThreshChange(0,0);
}
voidThreshChange(int,void*){
Canny(grayImg,cannyOutImg,ThreshValue,ThreshValue*2,3);
//寻找轮廓
findContours(cannyOutImg,vContours,vHierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point(0,0));
//会出轮廓
Matdrawing=Mat::zeros(cannyOutImg.size(),CV_8UC3);
for(inti=0;i<vContours.size();i )
{
Scalarcolor=Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255));
drawContours(drawing,vContours,i,color,2,8,vHierarchy,0,Point());
}
imshow("ThreshWindow",drawing);
}
intmain(){
test();
waitKey(0);
return0;
}
效果图: