一、说明
轮廓的多边形逼近指的是:使用多边形来近似表示一个轮廓。 多边形逼近的目的是为了减少轮廓的顶点数目。 多边形逼近的结果依然是一个轮廓,只是这个轮廓相对要粗旷一些。
函数原型:void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed) 函数作用:轮廓的多边形逼近 参数说明:curve 存储在一个2D点的输入向量:std::vector or Mat。 approxCurve 近似的结果。类型应符合输入曲线的类型。 epsilon 参数指定的逼近精度。这是原始曲线之间的最大距离及其迭代逼近。 closed 如果为true,近似的曲线是闭合的(第一个和最后一个顶点连接)。否则,它是未关闭。
二、例程
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace cv; using namespace std; 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 ); Mat canny_output; vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// 二值化 Canny( src_gray, canny_output, thresh, thresh*2, 3 ); //找轮廓 findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); /// 多边形逼近轮廓 vector<vector<Point> > contours_poly( contours.size() ); //画出轮廓 Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 ); Mat drawing_poly = Mat::zeros( canny_output.size(), CV_8UC3 ); for( int i = 0; i< contours.size(); i++ ) { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true ); Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) ); drawContours( drawing, contours, i, color, CV_FILLED, 8, hierarchy, 0, Point() ); drawContours( drawing_poly, contours_poly, i, color, CV_FILLED, 8, hierarchy, 0, Point() ); } //显示 namedWindow( "Contours", CV_WINDOW_AUTOSIZE ); imshow( "Contours", drawing ); imshow( "Contours_poly", drawing_poly ); waitKey(0); return(0); }
三、结果
效果如下图所示。