最近在做目标跟踪相关的实验,其中牵涉到最小外接矩形或最小外接圆形的函数使用,把自己实验的过程记录一下,希望可以帮助大家。
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);
枚举定义如下:
- enum
- {
- /* 8bit, color or not */
- CV_LOAD_IMAGE_UNCHANGED =-1,
- /* 8bit, gray */
- CV_LOAD_IMAGE_GRAYSCALE =0,
- /* ?, color */
- CV_LOAD_IMAGE_COLOR =1,
- /* any depth, ? */
- CV_LOAD_IMAGE_ANYDEPTH =2,
- /* ?, any color */
- CV_LOAD_IMAGE_ANYCOLOR =4
- };
flag=o,返回灰度图
flag>0;返回三通道彩色图
flag<0;负值一般不取,因为不需要alpha通道。