我正在分割岩石。为了比较细分结果,我:
问题是:
->排序不给出n个最大的轮廓(例如5)。我不明白为什么。
这是输入图像:
排序后的所有轮廓:
然后,前5个轮廓图像:
我期望的结果只是最大轮廓的前5或n个。具体来说,第一大和第二大应该是rgb图像右侧的棕色大块岩石。
用于排序的代码来自page 417
我的代码(其中的一部分)显示了前5个轮廓,如下所示:
// Sorting by descending order
struct AreaCmp {
AreaCmp(const vector<float>& _areas) : areas(&_areas) {}
bool operator()(int a, int b) const { return (*areas)[a] > (*areas)[b]; }
const vector<float>* areas;};
int main{
std::vector<std::vector<cv::Point>> contours;
std::vector<cv::Vec4i> hierarchy;// There is no hierarchy formed because of CV_RETR_LIST
cv::findContours(input_image, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);//CV_CHAIN_APPROX_SIMPLE
std::vector<int> sortIdx(contours.size());
std::vector<float> areas(contours.size());
for( int n = 0; n < (int)contours.size(); n++)
{
sortIdx[n] = n;
areas[n] = cv::contourArea(contours[n], false);
}
std::sort(sortIdx.begin(), sortIdx.end(), AreaCmp(areas));
FINROC_LOG_PRINT(DEBUG, "sortIdx size", (int)sortIdx.size());
FINROC_LOG_PRINT(DEBUG, "contours size", (int)contours.size());
int q = 0;
for( int n = 0; n < (int)sortIdx.size(); n++)
{
int idx = sortIdx[n];
cv::drawContours(input_rgb_image, contours, idx, cv::Scalar(0,255,0), 1, 8, hierarchy);
q++;
if(q > 5) break; // to draw only the first 5
}
}