opencv学习笔记——计算轮廓外界矩形(有用的)
图像输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/62857c74108899508bd3c013f5278735.png)
代码部分
#include <iostream>
#include <vector>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("形状多.png");
if (img.empty())
{
cout << "输入为空";
return -1;
}
Mat img1, img2;
img.copyTo(img1);
img.copyTo(img2);
imshow("img", img);
Mat canny;
Canny(img, canny, 80, 160, 3, false);
imshow("", canny);
Mat kernal = getStructuringElement(0, Size(3, 3));
dilate(canny, canny, kernal);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(canny, contours, hierarchy, 0, 2, Point());
for (int n = 0; n < contours.size(); n++)
{
Rect rect = boundingRect(contours[n]);
rectangle(img1, rect, Scalar(0, 0, 255), 2, 8, 0);
RotatedRect rrect = minAreaRect(contours[n]);
Point2f points[4];
rrect.points(points);
Point2f cpt = rrect.center;
for (int i = 0; i < 4; i++)
{
if (i == 3)
{
line(img2, points[i], points[0], Scalar(0, 255, 0), 2, 8, 0);
break;
}
line(img2, points[i], points[i + 1], Scalar(0, 255, 0), 2, 8, 0);
}
circle(img2, cpt, 2, Scalar(255, 255, 0), 2, 8, 0);
}
imshow("max", img1);
imshow("min", img2);
waitKey(0);
return 0;
}