opencv6-最小外接矩形minAreaRect

最近在做目标跟踪相关的实验,其中牵涉到最小外接矩形或最小外接圆形的函数使用,把自己实验的过程记录一下,希望可以帮助大家。

minAreaRect()函数用于给定的2D点集,函数原型:

RotatedRect  minAreaRect(InputArray  points);

只有一个输入参数,类型可以是vector<>或Mat


minEnclosingCircle()函数原型:

void minEnclosingCircle(InputArray points,CV_OUT  Point2f& center, CV_OUT float& radius);

第一个参数是要求的最小外接圆的点集或向量

第二个参数是最小外接圆的中心坐标,类型是Point2f

第三个参数是圆的半径,类型是float

#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>

using namespace std;
using namespace cv;

int main(){

	Mat image=imread("7.jpg",0);
	imshow("image",image);

	Mat result,threshold_out;
	//cvtColor(image,result,COLOR_BGR2GRAY);
	blur(image,result,Size(3,3));
	

	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	
	threshold(result,threshold_out,0,255,CV_THRESH_OTSU);//Otsu法:灰度图像的自动阈值分割
	erode(threshold_out,threshold_out,3);
	imshow("threshold image",threshold_out);
	//寻找最外层轮廓
	findContours(threshold_out,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_NONE,Point());

    //最小外接矩形画布
	Mat imageContours=Mat::zeros(threshold_out.size(),CV_8UC1);
	//最小外接圆画布
	Mat imageContours1=Mat::zeros(threshold_out.size(),CV_8UC1);

	//绘制
	for(int i=0;i<contours.size();i++){
	
		//绘制轮廓
		drawContours(imageContours,contours,i,Scalar(255),1,8,hierarchy);
		drawContours(imageContours1,contours,i,Scalar(255),1,8,hierarchy);
		//绘制最小外接矩形
		RotatedRect rect=minAreaRect(contours[i]);
		Point2f Point[4];
		rect.points(Point);
		for(int j=0;j<4;j++){
		
			line(imageContours,Point[j],Point[(j+1)%4],Scalar(255),2);
		}

		//绘制最小外接圆
		Point2f center;
		float radius;
		minEnclosingCircle(contours[i],center,radius);
		circle(imageContours1,center,radius,Scalar(255),2);
	
	}

	imshow("rect",imageContours);
	imshow("circle",imageContours1);
	waitKey(0);
	return 0;

}
实验结果:实验效果图不是特别好,大家可以对获取的二值图进行形态学处理。

在实验期间遇到的问题:


解决办法是在获取图像时,要保证获取的图像格式是与二值化函数要求的一致。例如:在获取图片后,加个0,返回的就是灰度图像了。如果忽略这个参数,就表示载入的是三通道的彩色图像。

Mat image=imread("7.jpg",0);
枚举定义如下:

  1. enum  
  2. {  
  3. /* 8bit, color or not */  
  4.    CV_LOAD_IMAGE_UNCHANGED  =-1,  
  5. /* 8bit, gray */  
  6.    CV_LOAD_IMAGE_GRAYSCALE  =0,  
  7. /* ?, color */  
  8.    CV_LOAD_IMAGE_COLOR      =1,  
  9. /* any depth, ? */  
  10.    CV_LOAD_IMAGE_ANYDEPTH   =2,  
  11. /* ?, any color */  
  12.    CV_LOAD_IMAGE_ANYCOLOR   =4  
  13. }; 
如果不按着枚举取值,只需要记着

flag=o,返回灰度图

flag>0;返回三通道彩色图

flag<0;负值一般不取,因为不需要alpha通道。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值