(学习笔记) approxPolyDP函数 boundingRect函数

来源:互联网 发布:机械师软件 编辑:程序博客网 时间:2024/05/21 17:50

1、boundingRect函数

函数作用:

计算轮廓的垂直边界最小矩形,矩形是与图像上下边界平行的


2、boundingRect函数调用形式

C++: Rect boundingRect(InputArray points)

points

二维点集,点的序列或向量 (Mat


3、approxPolyDP函数

函数的作用:

对图像轮廓点进行多边形拟合

4、函数的调用形式

C++: void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)

参数详解;

InputArray curve:一般是由图像的轮廓点组成的点集

OutputArray approxCurve:表示输出的多边形点集

 double epsilon:主要表示输出的精度,就是另个轮廓点之间最大距离数,5,6,7,,8,,,,,

bool closed:表示输出的多边形是否封闭


#include "cv.h"    
#include "highgui.h"    
#include <stdio.h>   


#include <opencv2/opencv.hpp>
#include<opencv2/imgproc/imgproc.hpp>


using namespace std;
using namespace cv;


Mat src;
Mat  src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);


void thresh_callback(int, void*);


int main(int argc, char** argv)
{
src = imread("1.jpg", 1);


cvtColor(src, src_gray, CV_BGR2GRAY);
blur(src_gray, src_gray, Size(3, 3));


char* source_window = "Source";
namedWindow(source_window, CV_WINDOW_AUTOSIZE);
imshow(source_window, src);


createTrackbar("Threshold:", "Source", &thresh, max_thresh, thresh_callback);
thresh_callback(0, 0);


waitKey(0);
return 0;


}


void thresh_callback(int, void*)
{


Mat threshold_output;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
//Canny(src_gray, canny_Mat, thresh, thresh * 2, 3);
/// 使用Threshold检测边缘  
threshold(src_gray, threshold_output, thresh, 255, THRESH_BINARY);
findContours(threshold_output, contours, hierarchy,CV_RETR_TREE,CV_CHAIN_APPROX_SIMPLE, Point(0, 0));


/// 多边形逼近轮廓 + 获取矩形和圆形边界框  
vector<vector<Point>>contours_poly(contours.size());
vector<Rect> bondRect(contours.size());
vector<Point2f>center(contours.size());
vector<float>radius(contours.size());




for (int i = 0; i < contours.size(); i++)
{
approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true);
bondRect[i] = boundingRect(Mat(contours[i]));
minEnclosingCircle(contours[i], center[i], radius[i]);
}


/// 画多边形轮廓 + 包围的矩形框 + 圆形框  
Mat drawing = Mat::zeros(threshold_output.size(), CV_8UC3);
for (int i = 0; i < contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(src, contours, i, color, 1, 8, hierarchy, 0, Point());
drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point());
rectangle(drawing,bondRect[i].tl(),bondRect[i].br(),color,2,8,0);
// circle(drawing, center[i], (int)radius[i], color, 2, 8, 0);


}
namedWindow("contours", CV_WINDOW_AUTOSIZE);
imshow("contours", drawing);
namedWindow("contours_src", CV_WINDOW_AUTOSIZE);
imshow("contours_src", src);


}


approxPolyDP函数是opencv中利用来对指定的点集进行逼近,其逼近的精度是可设置的对应的函数为:

void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed);

例如:approxPolyDP(contourMat, approxCurve, 10, true);//找出轮廓的多边形拟合曲线

第一个参数 InputArray curve:输入的点集
第二个参数OutputArray approxCurve:输出的点集,当前点集是能最小包容指定点集的。画出来即是一个多边形;
第三个参数double epsilon:指定的精度,也即是原始曲线与近似曲线之间的最大距离。
第四个参数bool closed:若为true,则说明近似曲线是闭合的,反之,若为false,则断开。

该函数采用是道格拉斯-普克算法(Douglas-Peucker)算法来实现。该算法也以Douglas-Peucker算法和迭代终点拟合算法为名。算法的目的是给出由线段组成的曲线(在某些上下文中也称为折线),以找到具有较少点的相似曲线。 该算法基于原始曲线和简化曲线(即曲线之间的豪斯多夫距离)之间的最大距离定义“不相似”。 简化曲线由定义原始曲线的点的子集组成。

算法描述如下:

起始曲线是有序的一组点或线,距离维度ε> 0。该算法递归地划分线。 最初给出了第一点和最后一点之间的所有点。 它会自动标记要保存的第一个和最后一个点。 然后找到距离第一点和最后一点组成的线段的最远的点作为终点; 这一点在距离终点之间的近似线段的曲线上显然最远。 如果该点比线段更接近于ε,那么当前未被标记的任何点将被保存,而没有简化的曲线比ε更差的可以丢弃。

如果离线段最远的点距离近似值大于ε,则必须保留该点。 该算法以第一个点和最远点递归地调用自身,然后以最远点和最后一个点(包括最远点被标记为保留)递归调用自身。
当递归完成时,可以生成一个新的输出曲线,其中包括所有且仅标记为保留的点。

非参数Ramer-Douglas-Peucker 
ε的选择通常是用户定义的。 像大多数线拟合/多边形近似/主点检测方法一样,通过使用由于数字化/量化的误差界限作为终止条件,可以使其非参数化[1] 这种非参数RDP算法[2]的MATLAB代码在这里可用[3]

伪代码:

假设输入是基于一一数组

function DouglasPeucker(PointList[], epsilon)    // Find the point with the maximum distance    dmax = 0    index = 0    end = length(PointList)    for i = 2 to ( end - 1) {        d = perpendicularDistance(PointList[i], Line(PointList[1], PointList[end]))         if ( d > dmax ) {            index = i            dmax = d        }    }    // If max distance is greater than epsilon, recursively simplify    if ( dmax > epsilon ) {        // Recursive call        recResults1[] = DouglasPeucker(PointList[1...index], epsilon)        recResults2[] = DouglasPeucker(PointList[index...end], epsilon)        // Build the result list        ResultList[] = {recResults1[1...length(recResults1)-1], recResults2[1...length(recResults2)]}    } else {        ResultList[] = {PointList[1], PointList[end]}    }    // Return the result    return ResultList[]end
该算法用于处理矢量图形 和制图综合。该算法广泛应用于机器人技术[4]中,对旋转量程扫描仪采集的范围数据进行简化和去噪; 在这个领域中,它被称为分裂合并算法,归因于Duda和Hart。

该算法的复杂度可以利用线性递归来描述T(n) = 2T(n2) + O(n),其具有T(n)∈Θ(n log n)的公知解决方案(通过主定理)。

 然而,最坏情况的复杂度是Θ(n2)。

源码:

   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <math.h>
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout<< "\nThis program illustrates the use of findContours and drawContours\n"
<< "The original image is put up along with the image of drawn contours\n"
<< "Usage:\n"<< "./contours2\n"
<< "\nA trackbar is put up which controls the contour level from -3 to 3\n"
<< endl;
}
const int w = 500;
int levels = 3;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
static void on_trackbar(int,void*)
{
Mat cnt_img = Mat::zeros(w, w, CV_8UC3);
int _levels = levels - 3;
drawContours( cnt_img, contours, _levels <=0 ? 3 : -1, Scalar(128,255,255),
3, LINE_AA, hierarchy, std::abs(_levels) );
imshow("contours", cnt_img);
}
int main( int argc, char** argv)
{
cv::CommandLineParser parser(argc, argv,"{help h||}");
if (parser.has("help"))
{
help();
return 0;
}
Mat img = Mat::zeros(w, w, CV_8UC1);
//Draw 6 faces
for( int i = 0; i < 6; i++ )
{
int dx = (i%2)*250 -30;
int dy = (i/2)*150;
const Scalar white = Scalar(255);
const Scalar black = Scalar(0);
if( i == 0 )
{
for( int j = 0; j <= 10; j++ )
{
double angle = (j+5)*CV_PI/21;
line(img, Point(cvRound(dx+100+j*10-80*cos(angle)),
cvRound(dy+100-90*sin(angle))),
Point(cvRound(dx+100+j*10-30*cos(angle)),
cvRound(dy+100-30*sin(angle))), white,1, 8, 0);
}
}
ellipse( img, Point(dx+150, dy+100),Size(100,70),0, 0, 360, white, -1,8, 0 );
ellipse( img, Point(dx+115, dy+70),Size(30,20),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+185, dy+70),Size(30,20),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+115, dy+70),Size(15,15),0, 0, 360, white, -1,8, 0 );
ellipse( img, Point(dx+185, dy+70),Size(15,15),0, 0, 360, white, -1,8, 0 );
ellipse( img, Point(dx+115, dy+70),Size(5,5),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+185, dy+70),Size(5,5),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+150, dy+100),Size(10,5),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+150, dy+150),Size(40,10),0, 0, 360, black, -1,8, 0 );
ellipse( img, Point(dx+27, dy+100),Size(20,35),0, 0, 360, white, -1,8, 0 );
ellipse( img, Point(dx+273, dy+100),Size(20,35),0, 0, 360, white, -1,8, 0 );
}
//show the faces
namedWindow( "image",1 );
imshow( "image", img );
//Extract the contours so that
vector<vector<Point> > contours0;
findContours( img, contours0, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
contours.resize(contours0.size());
for( size_t k = 0; k < contours0.size(); k++ )
approxPolyDP(Mat(contours0[k]), contours[k],3, true);
namedWindow( "contours",1 );
createTrackbar( "levels+3","contours", &levels,7, on_trackbar );
on_trackbar(0,0);
waitKey();
return 0;
}

阅读全文
0 0
原创粉丝点击