分享

OpenCV-矩形边框cv::boundingRect

 翟天保的图书馆 2022-01-13

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

函数原型

cv::Rect boundingRect( InputArray array );

参数说明

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

输出:Rect类型的矩形信息,包括矩形尺寸和位置。

测试代码

#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::Rect rect = cv::boundingRect(cv::Mat(contours[i]));
cv::rectangle(result, rect, Scalar(255), 1);
}

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

return 0;
}

测试效果

图1 灰度原图
图2 阈值图
图3 连通区矩形框效果图

       这个函数得到的矩形框都是方正的,还有一个函数minAreaRect也可以得到最小包围矩形框,那个是带倾斜角度的,后面我会再写一篇文章介绍。

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

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多