Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
morphologyEx(Image_threshold, Image_morp, MORPH_OPEN, element);
morphologyEx(Image_morp, Image_morp, MORPH_CLOSE, element);
vector<vector<Point>> contours;
vector<Vec4i>hierarchy;
findContours(Image_morp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
boundingRect()用于获得最小外接矩阵的一些参数:boundingRect()函数的使用方法
获得轮廓的面积、周长:opencv学习笔记,利用contourArea和arcLength检测物体的轮廓面积和周长
vector<vector<Point>> contours;
vector<Vec4i>hierarchy;
findContours(Image_morp, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<vector<Point> > contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());
vector<int> xs, xy;
cout << "contours.size(): " << contours.size() << endl;
float image_area = 0.0;
for (int i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
boundRect[i] = boundingRect(Mat(contours[i]));
image_area += contourArea(contours[i]);
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<Vec4i>(), 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);