OpenCV-最小包围旋转矩形边框cv::minAreaRect

作者:翟天保Steven
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处 

函数原型

cv::RotatedRect minAreaRect( InputArray points );

参数说明

输入:InputArray类型的points,输入灰度图像或二维点集。

输出:RotatedRect类型的旋转矩形信息,即矩形四角点位置。

测试代码

#include <iostream>
#include <time.h>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
	cv::Mat src = imread("test.png",0);
	cv::Mat result = src.clone();
	cv::Mat th1;
	// 最大类间差法,也称大津算法
	threshold(result, th1, 0, 255, THRESH_OTSU);
	// 反相
	th1 = 255 - th1;
	// 确定连通区轮廓
	std::vector<std::vector<cv::Point> > contours;  // 创建轮廓容器
	std::vector<cv::Vec4i> 	hierarchy;
	cv::findContours(th1, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE, cv::Point());
	// 遍历轮廓显示矩形框
	for (int i = 0; i < contours.size(); ++i)
	{
		cv::RotatedRect rotatedrect = cv::minAreaRect(cv::Mat(contours[i]));
		// 存储旋转矩形的四个点
		cv::Point2f ps[4];
		rotatedrect.points(ps);
		std::vector<std::vector<cv::Point>> tmpContours;    // 创建一个InputArrayOfArrays 类型的点集
		std::vector<cv::Point> contour;
		for (int i = 0; i != 4; ++i) {
			contour.emplace_back(cv::Point2i(ps[i]));
		}
		// 插入到轮廓容器中
		tmpContours.insert(tmpContours.end(), contour);
		// 绘制轮廓,也就是绘制旋转矩形
		drawContours(result, tmpContours, -1, Scalar(0), 1, 16);  // 填充mask
	}

	imshow("original", src);
	imshow("thresh", th1);
	imshow("result", result);
	waitKey(0);

	return 0;
}

测试效果

图1 灰度原图
图2 阈值图
图3 旋转矩形框效果图

       这个函数得到的矩形框都是旋转的,与OpenCV-矩形边框cv::boundingRect 所讲的函数形成了鲜明对比。

       如果文章帮助到你了,可以点个赞让我知道,我会很快乐~加油!

© 版权声明
THE END
喜欢就支持一下吧
点赞915 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容