赞
踩
目录
Rect cv::boundingRect ( InputArray array )
示例代码:
- //轮廓最大外接矩阵
- void Contour_external_maxmatrix(Mat image) {
- Mat gray,binary;
- cvtColor(image,gray,COLOR_BGR2GRAY);//灰度化
- GaussianBlur(gray,gray,Size(9,9),2,2);//滤波
- threshold(gray,binary,170,255,THRESH_BINARY|THRESH_OTSU);//自适应二值化
- //轮廓检测
- vector<vector<Point>> contours;//轮廓
- vector<Vec4i> hierarchy;//存放轮廓结构变量
- findContours(binary,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
- //寻找轮廓的外接矩阵
- for(int n=0;n<contours.size();n++) {
- //最大外接矩阵
- Rect rect = boundingRect(contours[n]);
- rectangle(image, rect, Scalar(7, 67, 255), 2, 8, 0);
- }
- imwrite("/sdcard/DCIM/max.png",image);
- }
轮廓外接最大矩形的结果:
RotatedRect cv::minAreaRect ( InputArray points )
示例代码:
-
- //轮廓最小外接矩阵
- void Contour_external_minmatrix(Mat image){
- Mat gray,binary;
- cvtColor(image,gray,COLOR_BGR2GRAY);//灰度化
- GaussianBlur(gray,gray,Size(9,9),2,2);//滤波
- threshold(gray,binary,170,255,THRESH_BINARY|THRESH_OTSU);//自适应二值化
- //轮廓检测
- vector<vector<Point>> contours;//轮廓
- vector<Vec4i> hierarchy;//存放轮廓结构变量
- findContours(binary,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
- //寻找轮廓的外接矩阵
- for(int n=0;n<contours.size();n++) {
- //最小外接矩阵
- 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(image,points[i],points[0],Scalar(0,0,255,255),2,8,0);
- break;
- }
- line(image,points[i],points[i+1],Scalar(0,0,255,255),2,8,0);
- }
- //绘制矩阵中心
- circle(image,cpt,4,Scalar(0,0,255,255),-1,8,0);
- }
- imwrite("/sdcard/DCIM/min.png",image);
-
- }
轮廓外接最小矩形的结果:
void cv::approxPolyDP (InputArray curve,
OutputArray approxCurve,
double epsilon,
bool closed
)
示例代码:
-
- void drawapp(Mat result,Mat img2){
- for(int i=0;i<result.rows;i++){
- //最后一个坐标点与第一个坐标点连接
- if(i==result.rows-1){
- Vec2i point1=result.at<Vec2i>(i);
- Vec2i point2=result.at<Vec2i>(0);
- line(img2,point1,point2,Scalar(0,0,255,255),4,8,0);
- break;
- }
- Vec2i point1=result.at<Vec2i>(i);
- Vec2i point2=result.at<Vec2i>(i+1);
- line(img2,point1,point2,Scalar(0,0,255,255),4,8,0);
- }
-
- }
-
- //轮廓多边形拟合
- void Contour_external_matrix(Mat image){
- Mat gray,binary;
- cvtColor(image,gray,COLOR_BGR2GRAY);//灰度化
- // GaussianBlur(gray,gray,Size(9,9),2,2);//滤波
- // threshold(gray,binary,170,255,THRESH_BINARY|THRESH_OTSU);//自适应二值化
- //轮廓的发现与绘制
- vector<vector<Point>> contours;//轮廓
- vector<Vec4i> hierarchy;//存放轮廓结构变量
- findContours(gray,contours,hierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point());
- //绘制多边形
- for(int n=0;n<contours.size();n++) {
- //用最小外接矩阵求取轮廓中心
- RotatedRect rrect= minAreaRect(contours[n]);
- Point2f center=rrect.center;//最小外接矩阵的中心
- circle(image,center,2,Scalar(0,0,255,255),2,8,0);
- Mat result;
- approxPolyDP(contours[n],result,4,true);//多边形拟合
- drawapp(result,image);
- }
- imwrite("/sdcard/DCIM/matrix.png",image);
-
- }
多边形拟合的结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。