**〜更新〜**嗨,我有一个源文件,并将其转换为下面的图片,并且我的程序中有一个轮廓

void find_contour(int, void*, Mat _mat)
{
Mat edge_detect_canny;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(_mat, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
Mat drawing = Mat::zeros(_mat.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, i, color, 1, 8, hierarchy, 1, Point());
}
IMshow(drawing, "draw-Res", 0);
imwrite("c:\\draw.bmp", drawing);
int cs = contours.size();
cout << cs << "contour.size" << endl;
}
Run Code Online (Sandbox Code Playgroud)
效果很好,但我想添加边界框,为每个轮廓找到边界框以选择所有对象。我该怎么办?
您可以通过以下方式获得每个轮廓的边界框:
Rect box = boundingRect(contours[i]);
Run Code Online (Sandbox Code Playgroud)
您可以将其绘制为:
rectangle(drawing, box, color);
Run Code Online (Sandbox Code Playgroud)
因此,只需在for循环中添加以下两行:
Rect box = boundingRect(contours[i]);
rectangle(drawing, box, color);
Run Code Online (Sandbox Code Playgroud)