1 #include"stdafx.h" 2 #include <iostream> 3 4 using namespace cv; 5 using namespace std; 6 7 struct Select 8 { 9 Rect rect;//会被自动初始化为全零 10 bool flag,compute; 11 Select(){flag=0;compute=0;} 12 }; 13 static Select select; 14 static Point origin; 15 int roadSamplePick(Mat &img,Mat &composite,Rect&roadSampleRect); 16 17 static void onMouse(int event,int x,int y,int flag,void* param) 18 { 19 static Size size=*(Size*)param; 20 switch(event) 21 { 22 case CV_EVENT_MOUSEMOVE: 23 if(select.flag) 24 { 25 select.rect.x=origin.x<x?origin.x:x; 26 select.rect.y=origin.y<y?origin.y:y; 27 select.rect.width=abs(x-origin.x); 28 select.rect.height=abs(y-origin.y); 29 } 30 break; 31 case CV_EVENT_LBUTTONDOWN: 32 origin=Point(x,y); 33 select.flag=1; 34 break; 35 case CV_EVENT_LBUTTONUP: 36 select.flag=0;//不画矩形框 37 select.compute=1;//对选定区域进行计算 38 } 39 } 40 int roadSamplePick(Mat &img,Mat &composite,Rect&roadSampleRect){ 41 Mat hsv,img_hsv[3],tempcom; 42 Mat edgeh,edgev;//边缘 43 Scalar mean,dev; 44 cvtColor(img,hsv,CV_BGR2HSV); 45 GaussianBlur(hsv,hsv,Size(3,3),1.5); 46 hsv.assignTo(hsv,CV_32FC3); 47 split(hsv,img_hsv);//0色调,1饱和度,2亮度 48 Sobel(img_hsv[2],edgeh,-1,1,0);//垂直边缘检测(x- image derivative) 49 Sobel(img_hsv[2],edgev,-1,0,1);//水平边缘检测(y- image derivative) 50 tempcom=img_hsv[0]+img_hsv[1]+edgeh+edgev;//合成图像 51 //取得样本区域 52 53 Mat roadSample,roadSampleGray,road;//rect子图 54 if(roadSampleRect.y<0)//图像过小而不能取样 55 { 56 std::cout<<"enable to create road sample"<<std::endl; 57 return -1; 58 } 59 cout<<(double)img_hsv[0].data[0]<<" "<<(double)img_hsv[1].data[0]<<endl; 60 roadSample=tempcom(roadSampleRect);//获取采样区域 61 meanStdDev(roadSample,mean,dev); 62 imshow("sample",roadSample); 63 float *data=(float*)tempcom.data; 64 for(int i=0;i<tempcom.total();i++) 65 { 66 if(data[i]<mean.val[0]-3*dev.val[0]||data[i]>mean.val[0]+3*dev.val[0]) 67 data[i]=0; 68 else 69 data[i]=255; 70 } 71 tempcom.assignTo(composite,CV_8UC1); 72 imshow("composite",composite); 73 return 0; 74 75 } 76 77 78 int main(int argc, unsigned char* argv[]) 79 { 80 Mat img,choose; 81 Size size; 82 //交互初始化 83 img=imread("test2.png"); 84 size=img.size(); 85 namedWindow("image"); 86 setMouseCallback("image",onMouse,(void*)&size); 87 imshow("image",img); 88 89 while(1) 90 { 91 if(select.flag) 92 { 93 choose=img.clone(); 94 rectangle(choose,select.rect,Scalar(255,0,0),3,8,0); 95 imshow("image",choose); 96 } 97 if(select.compute) 98 { 99 Mat composite; 100 roadSamplePick(img,composite,select.rect); 101 select.compute=0; 102 } 103 if(waitKey(20)=='q')//退出 104 break; 105 } 106 107 return 0; 108 }