opencv的contour轮廓排序

来源:互联网 发布:淘宝上怎么设置折扣 编辑:程序博客网 时间:2024/06/05 05:54

原文地址:http://blog.csdn.net/weif6565/article/details/41078201

1 找轮廓findContours

findContours有两个接口,区别在于需不需要输出hierarchy层次结构(可用于分析轮廓间关系,一般比较少用到)。

直接找最外层轮廓RETR_EXTERNAL,结果输出全部轮廓点CHAIN_APPROX_NONE

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. vector<vector<Point>> contours;  
  2. findContours(edges_D,contours,RETR_EXTERNAL,CHAIN_APPROX_NONE);  


2 轮廓大小排序

找完轮廓后,绝大部分需求就是再获取最大轮廓,简单的可以按照轮廓周长或轮廓面积来排序。


排序函数直接用std库:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. std::sort(contours.begin(),contours.end(),ContoursSortFun);  


需要另外声明排序规则函数ContoursSortFun

按轮廓周长(轮廓点数量)排序:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static inline bool ContoursSortFun(vector<cv::Point> contour1,vector<cv::Point> contour2)  
  2. {  
  3.     return (contour1.size() > contour2.size());  
  4. }  


按轮廓面积排序:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. static inline bool ContoursSortFun(vector<cv::Point> contour1,vector<cv::Point> contour2)  
  2. {  
  3.     return (cv::contourArea(contour1) > cv::contourArea(contour2));  
  4. }  

排完续后,contours中第一个元素contours[0]即是最大轮廓.


3 绘制最大轮廓

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. Mat Img(edges_D.size(),CV_8UC3,Scalar(0));  
  2. drawContours(Img,contours,0,Scalar(255,0,0),-1);  

drawContours中第3个参数为0说明绘制第一个轮廓;最后一个参数-1代表绘制时填充轮廓,若大于0则指轮廓厚度。


1 0