- findContours函数的使用
//查找前景的区域 vector> contours; vector hierarchy; findContours(Image_morp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
自己写的代码:用于得到轮廓的最小外界矩阵、最小外接圆、轮廓的面积等
//查找前景的区域 vector> contours; vector hierarchy; findContours(Image_morp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0)); //cout << "查找前景的区域" << endl; vector > contours_poly(contours.size()); vector boundRect(contours.size()); vector center(contours.size()); vector radius(contours.size()); cout << "查找前景的区域-定义存储器" << endl; vector xs, xy; cout << "contours.size(): " << contours.size() << endl; if (contours.size() == 0) { cout << "没有任何前景" << endl; return 0; } float image_area = 0.0; for (int i = 0; i < contours.size(); i++) { approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true); cout << "进入函数" << endl; boundRect[i] = boundingRect(Mat(contours[i])); image_area += contourArea(contours[i]); cout << "是空的" << endl; cout << boundRect[i].x << " ii " << endl; cout << boundRect[i].y << " ii " << endl; cout << boundRect[i].width << " ii " << endl; cout << boundRect[i].height << " ii " << endl; cout << boundRect[i] << " ii " << endl; xs.push_back(boundRect[i].x); xs.push_back(boundRect[i].x + boundRect[i].width); xy.push_back(boundRect[i].y); xy.push_back(boundRect[i].y + boundRect[i].height); minEnclosingCircle(contours[i], center[i], radius[i]); } int x_max, x_min, y_max, y_min; x_max = *max_element(xs.begin(), xs.end()); x_min = *min_element(xs.begin(), xs.end()); y_max = *max_element(xy.begin(), xy.end()); y_min = *min_element(xy.begin(), xy.end()); cout << "x_max: v " << x_max << endl; cout << "x_min: v " << x_min << endl; cout << "y_max: v " << y_max << endl; cout << "y_min: v " << y_min << endl; cout << "src.col: v " << pBkImage.cols << endl; cout << " src.rows: v " << pBkImage.rows << endl; cout << " 总面积为: " << image_area << endl; //画出矩阵和圆形 Mat drawing = Mat::zeros(Image_threshold.size(), CV_8UC3); for (int i = 0; i < contours.size(); i++) { Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); drawContours(drawing, contours_poly, i, color, 1, 8, vector (), 0, Point()); rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0); circle(drawing, center[i], (int)radius[i], color, 2, 8, 0); } //显示在一个窗口 namedWindow("Contours", CV_WINDOW_AUTOSIZE); imshow("Contours", drawing); waitKey(0);



