1 void getTemplate(void) { 2 3 Mat src =frame; 4 cvtColor(src,src,COLOR_BGR2GRAY); 5 // namedWindow("input image", CV_WINDOW_AUTOSIZE); 6 // imshow("input image", src); 7 8 Rect roi_rect = Rect(10, 10,src.cols-20, src.rows-20); 9 Mat ROI_Image = src(roi_rect); 10 imshow("ROI image", ROI_Image); 11 12 Mat ROI_binary; 13 threshold(ROI_Image, ROI_binary, 0, 255, THRESH_BINARY | THRESH_OTSU); 14 15 Mat kernel = getStructuringElement(MORPH_RECT, Size(7, 7), Point(-1, -1)); 16 morphologyEx(ROI_binary, ROI_binary, MORPH_OPEN, kernel); 17 // imshow("ROI_binary image", ROI_binary); 18 19 Mat canny_output; 20 Canny(ROI_binary, canny_output, 100, 100 * 2); 21 22 vector<vector<Point>> contours; 23 vector<Vec4i> hireachy; 24 findContours(canny_output, contours, hireachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); 25 26 cvtColor(ROI_Image, ROI_Image, COLOR_GRAY2BGR); 27 28 //获取轮廓最大的宽和高 29 double maxh = 0, maxw = 0; 30 for (size_t t = 0; t < contours.size(); t++) { 31 Rect rect = boundingRect(contours[t]); 32 if (rect.height > maxh) maxh = rect.height; 33 if (rect.width > maxw) maxw = rect.width; 34 35 } 36 37 //筛选轮廓 38 int num[14]; 39 int i = 0; 40 for (size_t t = 0; t < contours.size(); t++) { 41 Rect rect = boundingRect(contours[t]); 42 if (rect.height > maxh*0.7 || rect.width > maxw*0.7) 43 { 44 rectangle(ROI_Image, rect, Scalar(0, 0, 255), 2); 45 num[i++] = t; 46 } 47 } 48 49 for (int i = 0; i < 14; i++) 50 cout << "num:" << num[i] << endl; 51 //Rect rect = boundingRect(contours[num[3]]); 52 // = ROI_Image(rect); 53 //imshow("digital", digital); 54 imshow("drawControus", ROI_Image); 55 }