1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include<opencv2/opencv.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include<iostream> #include<vector> #include<time.h>
using namespace cv; using namespace std;
int main() { VideoCapture capture("video.mp4"); while (1) { clock_t start,finish; double totaltime; start=clock(); Mat frame,img_hsv,img_hsv2; capture >> frame; if(frame.empty()) continue; imshow("原图",frame); cvtColor(frame,img_hsv,CV_BGR2HSV); Scalar lowerb = Scalar(105, 43, 176); Scalar upperb = Scalar(113, 255, 255); inRange(img_hsv, lowerb, upperb, img_hsv2); imshow("img_hsv2",img_hsv2); Mat element=getStructuringElement(MORPH_RECT,Size(11,11)); morphologyEx(img_hsv2,img_hsv2,MORPH_ERODE,element); Mat element2=getStructuringElement(MORPH_RECT,Size(16,17)); morphologyEx(img_hsv2,img_hsv2,MORPH_DILATE,element2); imshow("腐蚀膨胀",img_hsv2); vector<vector<Point>> contours; vector<Vec4i> hierarchy; findContours(img_hsv2,contours,hierarchy,CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); vector<Rect> boundRect(contours.size()); int a=0;float b=0; for(unsigned int i=0; i<contours.size();i++) { if(hierarchy[i][3]!=-1) { boundRect[i] = boundingRect( Mat(contours[i]) ); if( (float)boundRect[i].height/boundRect[i].width>1 ) { if((float)boundRect[i].height/boundRect[i].width>b) { b=(float)boundRect[i].height/boundRect[i].width; a=i; } } } } } vector<Rect> boundRect2(contours.size()); for(unsigned int i=0; i<contours.size();i++) { boundRect2[i] = boundingRect( Mat(contours[i]) ); if(boundRect2[i].height>30) if( boundRect[a].x > boundRect2[i].x && boundRect[a].x < (boundRect2[i].x+boundRect2[i].width) && boundRect[a].y > boundRect2[i].y && boundRect[a].y < (boundRect2[i].y+boundRect2[i].height )) rectangle( frame, boundRect2[i].tl(), boundRect2[i].br(), Scalar(0,0,255),4 ); } imshow("输出",frame); finish=clock(); totaltime=(double)(finish-start)/CLOCKS_PER_SEC; cout<<"帧率"<<1/totaltime<<endl; waitKey(1); cout<<"************************************************************"<<endl; } cin.get(); return 0; }
|