OpenCV C ++:按轮廓区域对轮廓进行排序 [英] OpenCV C++: Sorting contours by their contourArea

查看:2630
本文介绍了OpenCV C ++:按轮廓区域对轮廓进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据轮廓区域的大小对轮廓进行排序?

How can I sort contours by the size of their contour areas? And how can I get the biggest/smallest one?

推荐答案

您可以使用 std :: sort 使用自定义比较函数对象

You can use std::sort with a custom comparison function object

// comparison function object
bool compareContourAreas ( std::vector<cv::Point> contour1, std::vector<cv::Point> contour2 ) {
    double i = fabs( contourArea(cv::Mat(contour1)) );
    double j = fabs( contourArea(cv::Mat(contour2)) );
    return ( i < j );
}

用法:

[...]

// find contours
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( binary_image, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

// sort contours
std::sort(contours.begin(), contours.end(), compareContourAreas);

// grab contours
std::vector<cv::Point> biggestContour = contours[contours.size()-1];
std::vector<cv::Point> smallestContour = contours[0];

这篇关于OpenCV C ++:按轮廓区域对轮廓进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆