写c++ opencv画出最小外接矩形
时间: 2023-03-27 12:04:48 浏览: 115
可以使用 OpenCV 中的函数 cv::minAreaRect() 来计算最小外接矩形,具体实现如下:
1. 首先,读入图像并将其转换为灰度图像。
2. 对灰度图像进行二值化处理,得到二值图像。
3. 使用函数 cv::findContours() 找到二值图像中的轮廓。
4. 对每个轮廓,使用函数 cv::minAreaRect() 计算其最小外接矩形。
5. 使用函数 cv::drawContours() 将最小外接矩形绘制在原始图像上。
下面是代码示例:
```
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图像并转换为灰度图像
Mat img = imread("test.jpg");
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
// 对灰度图像进行二值化处理
Mat binary;
threshold(gray, binary, , 255, THRESH_BINARY | THRESH_OTSU);
// 找到二值图像中的轮廓
vector<vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 对每个轮廓,计算其最小外接矩形并绘制在原始图像上
for (int i = ; i < contours.size(); i++)
{
RotatedRect rect = minAreaRect(contours[i]);
Point2f vertices[4];
rect.points(vertices);
for (int j = ; j < 4; j++)
{
line(img, vertices[j], vertices[(j + 1) % 4], Scalar(, , 255), 2);
}
}
// 显示结果
imshow("result", img);
waitKey();
return ;
}
```