基于c++下opencv绘制最大外接矩形并在矩形上标注颜色的代码
时间: 2023-04-05 08:01:41 浏览: 178
以下是基于 C 下 OpenCV 绘制最大外接矩形并在矩形上标注颜色的代码:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("test.jpg");
if (img.empty())
{
cout << "Could not read the image" << endl;
return 1;
}
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
blur(gray, gray, Size(3, 3));
Canny(gray, gray, 100, 200, 3);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(gray, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
vector<vector<Point>> contours_poly(contours.size());
vector<Rect> boundRect(contours.size());
for (size_t i = 0; i < contours.size(); i++)
{
approxPolyDP(contours[i], contours_poly[i], 3, true);
boundRect[i] = boundingRect(contours_poly[i]);
}
Scalar color = Scalar(0, 0, 255);
for (size_t i = 0; i < contours.size(); i++)
{
rectangle(img, boundRect[i].tl(), boundRect[i].br(), color, 2);
}
imshow("Result", img);
waitKey(0);
return 0;
}
```
希望能对您有所帮助。
阅读全文